C# 在响应后WebAPI中发送Cookie
我正在尝试在对用户进行身份验证后向其发送cookie。一切都很完美,响应是在我的代码中构建的,但即使在客户端得到响应后,浏览器中也没有保存cookie(通过chrome F12->Resources检查) 注意:我可以看到用我的cookie以fiddler发送的响应: 我想知道出了什么问题,为什么浏览器不保存cookie 下面是处理Post请求的WebAPI函数:C# 在响应后WebAPI中发送Cookie,c#,http,post,cookies,asp.net-web-api,C#,Http,Post,Cookies,Asp.net Web Api,我正在尝试在对用户进行身份验证后向其发送cookie。一切都很完美,响应是在我的代码中构建的,但即使在客户端得到响应后,浏览器中也没有保存cookie(通过chrome F12->Resources检查) 注意:我可以看到用我的cookie以fiddler发送的响应: 我想知道出了什么问题,为什么浏览器不保存cookie 下面是处理Post请求的WebAPI函数: public HttpResponseMessage Post([FromBody]User user) {
public HttpResponseMessage Post([FromBody]User user)
{
IDal dal = new ProGamersDal();
var currentUser = dal.GetUser(user.Username, user.Password);
if (currentUser == null)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Bad request.");
}
else
{
var res = new HttpResponseMessage();
var cookie = new CookieHeaderValue("user",JsonConvert.SerializeObject(new ReponseUser(){username = currentUser.Username, role = currentUser.Role}));
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
res.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return res;
}
}
我发现了问题所在,因为在Firefox中保存了cookie 在chrome中,您不能将cookie设置为“localhost”的域,因为它被视为无效域(有效域中必须包含两个点),因此cookie无效 为了解决此问题,如果是localhost,您应该:
cookie.Domain = Request.RequestUri.Host == "localhost" ? null : Request.RequestUri.Host;
我发现了问题所在,因为在Firefox中保存了cookie 在chrome中,您不能将cookie设置为“localhost”的域,因为它被视为无效域(有效域中必须包含两个点),因此cookie无效 为了解决此问题,如果是localhost,您应该:
cookie.Domain = Request.RequestUri.Host == "localhost" ? null : Request.RequestUri.Host;
您的图像显示“请求”标题。。。“响应”标题中有哪些值?请求标题包含cookie以及您的图像显示的“请求”标题。。。“响应”标头中有哪些值?请求标头也包含cookie