AspNet.WebApi.CookiesPassthrough
1.0.0
允許您在WebAPI控制器中添加iHttpactionResult的cookie。
內容
有幾種方法可以將cookie添加到WebAPI中的響應中。根據文檔的說法,推薦的方法是使用resp.Headers.AddCookies(cookies)擴展方法,但存在一些缺點:
= cookie值中的char。CookieHeaderValue支持名稱值對,此類集合將以cookie-name=key1=value1&key2=value2表示,但是如果您嘗試通過僅通過字符串進行設置,則將編碼集合。直接通過Cookie Collection字符串對於通過服務傳遞Cookie值的情況,例如與基於舊版Cookie的API集成。另一種方法是通過HttpContext在httpresponse.cookies上設置cookie(檢查示例),但還有更嚴重的缺點:
HttpContext是不好的實踐,因為您無法將它們放在自宿主中。new Thread() 。最好將簡單的API用於IHttpActionResult ,其中有描述的缺點。也可以提供本地主機支持或“為所有子域啟用這些cookie”功能。
您可以通過Nuget安裝aspnet.webapi.cookiespasspasspasspass。
var cookieDescriptors = new [ ]
{
// simple cookie with Path=/
new CookieDescriptor ( "test-cookie" , "1" ) ,
// encode
new CookieDescriptor ( "test-cookie2" , "2=" ) {
CodeStatus = CookieCodeStatus . Encode
} ,
// expires, secure, httponly + decode
new CookieDescriptor ( "test-cookie3" , "a%3D3" ) {
Secure = true ,
CodeStatus = CookieCodeStatus . Decode ,
HttpOnly = true ,
Expires = new DateTime ( 2118 , 1 , 1 )
} ,
// path will be added and no decode or encode
new CookieDescriptor ( "test-cookie4" , "4%3D=" ) {
Path = "/subfolder/"
} ,
} ;
// also you can use Request.GetReferrerHost() to get referrer's host which is useful when you're developing AJAX API
return Ok ( ) . AddCookies ( cookieDescriptors , Request . GetRequestHost ( ) ) ;您可以為所有子域啟用cookie:
// domain will be ".example.org"
return Ok ( ) . AddCookies ( cookieDescriptors , "example.org" ) . EnableCookiesForAllSubdomains ( ) ;
// same, domain will be ".example.org"
return Ok ( ) . AddCookiesForAllSubdomains ( cookieDescriptors , "www.example.org" ) ;
// or even this
return Ok ( )
. AddCookiesForAllSubdomains ( cookieDescriptorsForAllSubdomains , "example.org" )
. AddCookies ( cookieDescriptorsForOneDomain , "example.com" )
. AddCookies ( cookieDescriptorsForAnotherDomainAndAllSubdomains , "www.example.net" )
. EnableCookiesForAllSubdomains ( ) ; 瀏覽器在Local主機Cookie方面存在問題。如果您將域指定為localhost甚至.localhost則根本不會將其添加到響應中,以使幾乎所有瀏覽器的localhost使用Local -Host工作。
當您致電.EnableCookiesForAllSubdomains()或使用.AddCookiesForAllSubdomains(...)將應用以下域轉換:
"localhost" => " "
" . localhost " => " "
"www.localhost" => ".www.localhost"
"www.localhost.ru" => ".localhost.ru"
"www.org" => ".www.org"
".www.org" => ".www.org"
"example.org" => ".example.org"
"www.example.org" => ".example.org"
".www.example.org" => ".www.example.org" 檢查AspNet.WebApi.CookiesPassthrough.Example項目。