ASP.NET Mvc Api: 设置cookie然后302/303重定向丢失cookie
ASP.NET Mvc Api: Set cookie then 302/303 Redirect loses the cookie
我有一个 API 操作,returns 一个 HttpResponseMessage。
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 的域和路径属性。
我的cookies已经添加了Path
,但是问题还是没有解决
经过很长一段时间,我终于通过删除web.config
中的session状态配置解决了这个问题:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<!--<sessionState cookieless="false" timeout="30" mode="StateServer" stateConnectionString="tcpip=localhost:42424" />-->
</system.web>
</configuration>
评论后可以加set-cookie
header<sessionState>
.
希望对你有所帮助,谢谢。
我有一个 API 操作,returns 一个 HttpResponseMessage。 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 的域和路径属性。
我的cookies已经添加了Path
,但是问题还是没有解决
经过很长一段时间,我终于通过删除web.config
中的session状态配置解决了这个问题:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<!--<sessionState cookieless="false" timeout="30" mode="StateServer" stateConnectionString="tcpip=localhost:42424" />-->
</system.web>
</configuration>
评论后可以加set-cookie
header<sessionState>
.
希望对你有所帮助,谢谢。