我有一个返回HttpResponseMessage的API Action 。
API地址类似于:http://localhost/login?authcode=xxx
API操作执行一些登录身份验证,并将用户重定向到注册页面或欢迎页面。代码如下:
var response = new HttpResponseMessage();
var cookie = new CookieHeaderValue("token", "ThisIsTheTokenNeeded");
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
response.StatusCode = HttpStatusCode.Found;
response.Headers.Location = new Uri("http://localhost/welcome.html");
return response;
在welcome.html中,我使用“document.write(document.cookie)”,但看不到名为“token”的cookie。一些它是如何迷路的。谁能告诉我如何完成此工作,或者此体系结构毕竟不正确?
最佳答案
我找到了答案。范围未设置。在我的原始代码中,缺少以下行。
cookie.Path = "/";
因为重定向到另一个页面,所以即使在同一域下,该cookie在不同页面上也无效。如果未设置路径,则该cookie仅对以http://localhost/login?authcode=xxx为目标的原始请求有效
今天,我了解到,在声称有人吃了它之前,我需要仔细检查cookie的域和路径属性。
关于ASP.NET Mvc Api : Set cookie then 302/303 Redirect loses the cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32219664/