Click here to Skip to main content
15,030,781 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If I have a form/view that will display 1 or more partial views based on user responses. Where do I need to place the AntiForgeryToken? In the parent view? In the partial views? Both?

Currently, I have it in the partial views, but we are occasionally getting an error:

Type:System.Web.Mvc.HttpAntiForgeryException
Message:A required anti-forgery token was not supplied or was invalid.

The error is reported in production only, we are unable to reproduce it on developer machines (typical).

My theory is that when multiple partial views are represented a mismatch of tokens occurs and the error is reported. My thinking is to move the token to the main/parent view.

Am I on the right track? Anybody had to deal with something similar?
Posted

1 solution

In your View(assuming razor), use the HTML helper for ValidateAntiForgeryToken inside the form:

@using (Html.BeginForm()) {
   @Html.ValidationSummary(true)
   @Html.AntiForgeryToken()
   <fieldset>
       </fieldset>



Then in the HttpPost method for the controller action, decorate it with the ValidateAntiForgeryToken attribute:

C#
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ModelType modelObj)
{
    if (ModelState.IsValid)
    {
        ///
    }

    return View(modelObj);
}
   
Comments
littleGreenDude 12-Mar-14 15:11pm
   
Thank you for the response. Yes, the razor assumption is correct. At the basic level I understand what you are saying. My question is more driven by what is the proper approach when dealing with partial views. Is there a token for each partial view, or the container as a whole?

Currently our form contains divs for 5 partial views. The user is responding to a list of certification questions, and based on responses 1 or more divs/partial views are displayed. Each partial view is accepted/declined (button select) and the form as a whole is submitted (button). Currently, each partial view has its own AntiForgeryToken and corresponding token validation in the controller (in the manner as you indicated).

With this approach we periodically see the System.Web.Mvc.HttpAntiForgeryException

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900