使用搜索机器人发送HTTP标头后,服务器无法修改Cookie

时间:2012-03-30 15:50:31

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

我不确定这里发生了什么,但有时我在尝试设置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);
                }

1 个答案:

答案 0 :(得分: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);
            }