获取Html.AntiForgeryToken会引发错误“服务器无法在发送HTTP标头后修改cookie”

时间:2015-09-09 19:35:53

标签: c# asp.net-mvc-4 cookies

当我尝试运行以下代码时:

<form id="__SendAjaxAntiForgery" action="#" method="post"><%= Html.AntiForgeryToken()%></form>

我收到以下错误
“服务器无法在发送HTTP标头后修改Cookie。”

堆栈跟踪读取

at System.Web.HttpResponse.BeforeCookieCollectionChange()
at System.Web.HttpCookieCollection.Set(HttpCookie cookie)
at System.Web.Helpers.AntiXsrf.AntiForgeryWorker.GetFormInputElement(HttpContextBase httpContext)
at System.Web.Helpers.AntiForgery.GetHtml()
at System.Web.Mvc.HtmlHelper.AntiForgeryToken()
at ASP.views_shared_site_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer)

只有当我打开2个选项卡并在其中一个选项卡上注销然后重新登录选项卡1时才会发生这种情况(这样我会得到一个新的AntiForgeryToken),然后转到选项卡2并刷新。

当我尝试获取“Html.AntiForgeryToken();”

时发生异常

2 个答案:

答案 0 :(得分:2)

浏览器中的两个选项卡被认为是与服务器相同的登录会话,这打破了防伪标记。如果您尝试使用两个浏览器(IE,Firefox,Chrome)而不是同一浏览器的两个选项卡或窗口,它应该可以正常工作。

答案 1 :(得分:1)

So this has nothing to do with the Anti-Forgery token. The Anti-Forgery token was working correctly in this instance. We had a toolbar that wasn't getting created correctly and that was causing an exception which in turn was redirecting them to the logout. Once we fixed making sure that the toolbar was created correctly then the Anti-Forgery token worked correctly. The only thing that I wasn't aware of when I started this process was that the order the annotations on the method is the order that MVC processes the rules. So we had our own rules and I moved those up the order and that led me to thinking about the problem in a different light.