【问题标题】:ASP.NET Mvc Api: Set cookie then 302/303 Redirect loses the cookieASP.NET Mvc Api:设置 cookie 然后 302/303 重定向丢失 cookie
【发布时间】:2015-11-20 01:58:14
【问题描述】:

我有一个返回 HttpResponseMessage 的 API 操作。 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。一些它是如何丢失的。谁能告诉我如何完成这项工作,或者这个架构毕竟不正确?

【问题讨论】:

    标签: asp.net api cookies http-redirect


    【解决方案1】:

    我找到了答案。范围未设置。在我的原始代码中,缺少以下行。

    cookie.Path = "/";
    

    因为重定向到另一个页面,即使在同一个域下,cookie在不同页面之间也是无效的。如果未设置路径,则 cookie 仅适用于针对 http://localhost/login?authcode=xxx 的原始请求

    今天我了解到,在声称有人吃了它之前,我需要仔细检查 cookie 的域和路径属性。

    【讨论】:

      【解决方案2】:

      我的cookies已添加Path,但问题仍未解决。

      搞了半天,终于解决了这个问题,把web.config中的session state config去掉了:

      <?xml version="1.0" encoding="utf-8"?>
      <configuration>
        <system.web>
          <!--<sessionState cookieless="false" timeout="30" mode="StateServer" stateConnectionString="tcpip=localhost:42424" />-->
        </system.web>
      </configuration>
      

      我可以在 cmets &lt;sessionState&gt; 之后添加 set-cookie 标头。

      希望对你有帮助,谢谢。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-27
        • 2011-07-29
        • 2010-10-11
        相关资源
        最近更新 更多