How can I use multiple ajax forms with AntiForgery

2019-03-31 05:45发布

问题:

When we have more than one possible form to post to the controller on the same cshtml page, the Antiforgery validation does not work. We went through the MVC3 code and we found the problem is in this part of the code:

if (!String.Equals(cookieToken.Value, formToken.Value, StringComparison.Ordinal)) {
            // error: form token does not match cookie token
            throw CreateValidationException();
}

The cshtml that we have is something like this:

@using (@Ajax.BeginForm()) {
    @Html.AntiForgeryToken()
    <input type="submit" class="buttonBlue" value="form1" />
}

@using (@Ajax.BeginForm()) {
    @Html.AntiForgeryToken()
    <input type="submit" class="buttonBlue" value="form2" />
}

Can you help me to fix this issue? We found that after removing one of the antiforgery tokens eveyrthing seems to work as expected.

We tried setting the machine key for the antiforgery and it didn't work either.

Regards.

回答1:

In order to use the AntiForgeryToken multiple times, I do the following. First, at the top of my view, I add the following line:

ViewBag.__RequestVerificationToken = @Html.AntiForgeryToken().ToString();

Then, in each form where I need the token, I add the following:

@Html.Raw(ViewBag.__RequestVerificationToken)