我用asp.net web api构建了一个小例子。我创建了一个api进行身份验证。当用户登录成功时,我尝试使用set-cookie响应头。但在下一个请求中,我无法在标题中找到cookie。有谁能够帮我?非常感谢!!!
if (repository.CheckValidUser(user))
{
var resp = new HttpResponseMessage();
var cookie = new CookieHeaderValue("Authorization-Token", RSAClass.Encrypt(user.Username));
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return resp;
}
else
{
throw new HttpResponseException(new HttpResponseMessage() { StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("Invalid user name or password.") });
}
我有一些关于我的请求的照片
答案 0 :(得分:2)
你应该创建一个DelegatingHanlder来保存cookie,例如:
public class MyCookieHandle : DelegatingHandler
{
async protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
//
// Other code for retrieve user information
//
var cookie = request.Headers.GetCookies("Authorization-Token").FirstOrDefault();
if (cookie == null)
{
cookie = new CookieHeaderValue("Authorization-Token", RSAClass.Encrypt(user.Username));
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = request.RequestUri.Host;
cookie.Path = "/";
}
HttpResponseMessage resp = await base.SendAsync(request, cancellationToken);
resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return resp;
}
}
此处有更多信息:HTTP Cookies in ASP.NET Web API