问题
When I attempt to run the following code:
<form id="__SendAjaxAntiForgery" action="#" method="post"><%= Html.AntiForgeryToken()%></form>
I get the following error
"Server cannot modify cookies after HTTP headers have been sent."
The stack trace reads
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)
This only happens when I have 2 tabs open and on one of the tabs I logout and then log back in on tab 1(and in doing so I get a new AntiForgeryToken) and then go to tab 2 and refresh.
The exception is occuring when I attempt to get "Html.AntiForgeryToken();"
回答1:
Two tabs in the browser are considered the same login session to the server, and this is breaking the anti forgery token. If you try it with two browsers (IE, Firefox, Chrome) instead of two tabs or windows of the same browser, it should work fine.
回答2:
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.
来源:https://stackoverflow.com/questions/32487816/getting-html-antiforgerytoken-throws-error-server-cannot-modify-cookies-after-h