我如何可以使用多个AJAX形式与同MVC3页面上防伪验证?多个、可以使用、形式、页面

2023-09-10 16:58:59 作者:帅的不明朗

当我们有多个可能的形式张贴到控制器相同的CSHTML页面上, 该防伪验证不起作用。我们经历了MVC3 code和我们发现的问题是在这部分的code:

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

这是我们的CSHTML是这样的:

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" />
}

你能不能帮我解决这个问题?我们发现,除去防伪标记之一后eveyrthing似乎正常工作。

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.

问候。

推荐答案

为了使用AntiForgeryToken多次,我这样做。首先,在我的观点上,我添加以下行:

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)