AspNet.WebApi.CookiesPassthrough
1.0.0
WebAPI 컨트롤러에서 ihttpactionResult 용 쿠키를 추가 할 수 있습니다.
내용물
Webapi의 응답에 쿠키를 추가하는 방법에는 여러 가지가 있습니다. 문서에 따르면 권장되는 방법은 resp.Headers.AddCookies(cookies) 확장 방법을 사용하는 것이지만 몇 가지 단점이 있습니다.
= 가 필요합니다.CookieHeaderValue 이름-값 쌍을 지원하며 이러한 컬렉션은 cookie-name=key1=value1&key2=value2 로 표시되지만 문자열을 전달하여 설정하려고 시도하면 컬렉션이 인코딩됩니다. 쿠키 컬렉션 문자열을 직접 통과하는 것은 서비스를 통해 쿠키 값을 전달하는 경우와 예를 들어 레거시 쿠키 기반 API와의 통합에 유용합니다. 또 다른 방법은 HttpContext 통해 httpresponse.cookies에서 쿠키를 설정하는 것입니다 (예제 점검 예). 그러나 더 심각한 단점이 있습니다.
HttpContext 사용하는 것은 셀프 호스트에서 얻을 수 없기 때문에 나쁜 관행입니다.new Thread() 의 잠재적 문제. IHttpActionResult 에 대한 간단한 API를 사용하는 것이 더 좋습니다. 또한 LocalHost 지원을 받거나 "모든 하위 도메인에 이러한 쿠키를 활성화"하는 것이 좋습니다.
Nuget을 통해 Aspnet.webapi.cookiespassthrough 패키지를 설치할 수 있습니다.
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 ( ) ) ;모든 하위 도메인에 대한 쿠키를 활성화 할 수 있습니다.
// 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 ( ) ; 브라우저에는 로컬 호스트 쿠키에 문제가 있습니다. 도메인을 localhost 또는 .localhost 로 지정하면 거의 모든 브라우저에 대해 LocalHost가있는 쿠키를 만들기 위해 응답에 전혀 추가되지 않습니다.
.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 프로젝트를 확인하십시오.