【问题标题】:Server cannot modify cookies after HTTP headers have been sent with search bots使用搜索机器人发送 HTTP 标头后,服务器无法修改 cookie
【发布时间】:2012-04-17 09:45:46
【问题描述】:

我不确定这里发生了什么,但有时我在尝试设置 cookie 时收到错误消息“Server cannot modify cookies after HTTP headers have been sent”。据我所知,它主要是某种搜索机器人。机器人是否禁用了 cookie 或其他什么?当我禁用 cookie 时,我无法重现它。我下面的代码在控制器中运行。看起来对吗?

                var cookie = new HttpCookie(Config.ApiCookie)
                {
                    HttpOnly = true,
                    Secure = false,
                    Value = authenticationResponse[SessionKey].ToString()
                };

                if (HttpContext.Current.Response.Cookies[Config.ApiCookie] != null)
                {
                    HttpContext.Current.Response.Cookies.Set(cookie);
                }
                else
                {
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }

【问题讨论】:

  • 您是否可能在设置 cookie 之前刷新任何数据(即发送响应)?这就是您描述的错误消息所包含的内容。
  • 我不这么认为,这就是为什么它让我感到困惑。
  • 你有异步的东西吗?我在这里看到的唯一可以做任何事情来使无效的是'authenticationResponse[SessionKey]'......尝试将其剥离设置为“test”或类似的值

标签: asp.net-mvc-3 cookies web-crawler


【解决方案1】:

问题出在有问题的 .Set 上。我改用下面的代码并解决了这个问题。

if (HttpContext.Current.Response.Cookies[Config.ApiCookie] != null)
            {
                HttpContext.Current.Response.Cookies[Config.ApiCookie].Value = cookie.Value;
            }
            else
            {
                HttpContext.Current.Response.Cookies.Add(cookie);
            }

【讨论】:

    猜你喜欢
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 2012-03-06
    • 2015-12-05
    • 2011-09-13
    相关资源
    最近更新 更多