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项目。