Is it possible to set a cookie during a redirect in ASP.NET?

妖精的绣舞 提交于 2019-11-26 23:10:53

问题


I am using ASP.NET. I either add or set a cookie (depending on whether the HttpRequest contains a cookie with specified key), and immediately afterward call Response.Redirect. The cookie is not set. Is this correct behavior? Is there something mutually exclusive about setting a cookie during an http response with a 302 status code?

Here's the source:

        if (context.HttpContext.Request.Browser.Cookies)
        {
            var cookies = context.HttpContext.Request.Cookies;
            var stateCookie = new HttpCookie(SR.session, clientState.SessionId.ToString());
            if (cookies.AllKeys.Contains(SR.session))
            {
                context.HttpContext.Response.Cookies.Set(stateCookie);
            }
            else
            {
                context.HttpContext.Response.Cookies.Add(stateCookie);
            }
        }

Here are the Response headers

  • X-AspNetMvc-Version - 2.0
  • Connection - Close
  • Cache-Control - private
  • Content-Type - text/html
  • Date - Sun, 20 Mar 2011 03:48:04 GMT
  • Location - http://localhost:3599/Home/Redirected
  • Server - ASP.NET Development Server/9.0.0.0
  • X-AspNet-Version - 2.0.50727

回答1:


After googling a bit it seems that yes, there can be problems with setting the cookie in the redirect response as it may be ignored by a few browsers. (It may make some sense, as the response is really telling the client to ignore the resource and get some other resource instead).

This has been discussed here already: Sending browser cookies during a 302 redirect

So I would change the architecture in a way that allows the page being redirected to to set the cookie.



来源:https://stackoverflow.com/questions/5366635/is-it-possible-to-set-a-cookie-during-a-redirect-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!