假设 cookie 是由 ApiController 本身设置的。它可以是任何组件,但说控制器会这样做,如下所示:
public HttpResponseMessage Get(int id)
{
var cookie = new CookieHeaderValue("abc", "12345");
cookie.Path = "/";
var response = Request.CreateResponse();
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return response;
}
同样,cookie 可以是任何 cookie,包括 FormsAuth。但我只是使用普通的cookie。如果您有消息处理程序,您可以简单地创建一个具有相同密钥的 HttpOnly 和安全 cookie,如下所示:
public class MyHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
var cookie = new CookieHeaderValue("abc", "12345");
cookie.Secure = true;
cookie.HttpOnly = true;
cookie.Path = "/";
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return response;
}
}
这样发送回客户端的 cookie 将是一个安全的 HttpOnly cookie。