2

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();"

user299967
  • 119
  • 2
  • 12

2 Answers2

2

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.

StingyJack
  • 19,041
  • 10
  • 63
  • 122
  • Two tabs in the browser of the same app ? – Kiquenet Dec 19 '18 at 16:45
  • @Kiquenet - two tabs in the same browser application. Two tabs in IE, two tabs in chrome, etc. If OP opens op one tab in IE and one tab in Chrome, they will not encounter this problem. When they logout of one tab, they are actually logging out of all tabs that may be open for that site in that browser.. – StingyJack Dec 20 '18 at 03:46
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.

user299967
  • 119
  • 2
  • 12