How can I use multiple ajax forms with AntiForgery validation on the same MVC3 page?

可紊 提交于 2019-12-21 05:39:25

问题


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)


来源:https://stackoverflow.com/questions/8271085/how-can-i-use-multiple-ajax-forms-with-antiforgery-validation-on-the-same-mvc3-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!