在 ASP.NET MVC 的 ajax post 中包含防伪标记。

14 浏览
0 Comments

在 ASP.NET MVC 的 ajax post 中包含防伪标记。

我在使用ASP.NET MVC 3时遇到了关于AntiForgery标记的ajax问题。我尝试了在jQuery Ajax calls and the Html.AntiForgeryToken()中提供的解决方案,现在token已经被传递:

var data = { ... } // with token, key is '__RequestVerificationToken'
$.ajax({
        type: "POST",
        data: data,
        datatype: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        url: myURL,
        success: function (response) {
            ...
        },
        error: function (response) {
            ...
        }
    });

当我删除[ValidateAntiForgeryToken]属性以查看是否将数据(包含令牌的数据)作为参数传递到控制器时,我可以看到它们被传递了。但出现了A required anti-forgery token was not supplied or was invalid.的消息,当我将属性放回去时。

有什么建议吗?

编辑

Antiforgerytoken是在表单中生成的,但我不使用提交操作来提交它。相反,我只是使用jquery获取令牌值,然后尝试Ajax post。

这是包含令牌的表单,位于顶部的主页:

@Html.AntiForgeryToken()

 

admin 更改状态以发布 2023年5月24日
0
0 Comments

另一种不那么JavaScript风格的方法,是我自己做的,大概是这样的:

首先,编写一个HTML帮助程序

public static MvcHtmlString AntiForgeryTokenForAjaxPost(this HtmlHelper helper)
{
    var antiForgeryInputTag = helper.AntiForgeryToken().ToString();
    // Above gets the following: 
    var removedStart = antiForgeryInputTag.Replace(@"", "");
    if (antiForgeryInputTag == removedStart || removedStart == tokenValue)
        throw new InvalidOperationException("Oops! The Html.AntiForgeryToken() method seems to return something I did not expect.");
    return new MvcHtmlString(string.Format(@"{0}:""{1}""", "__RequestVerificationToken", tokenValue));
}

它将返回一个字符串

__RequestVerificationToken:"P5g2D8vRyE3aBn7qQKfVVVAsQc853s-naENvpUAPZLipuw0pa_ffBf9cINzFgIRPwsf7Ykjt46ttJy5ox5r3mzpqvmgNYdnKc1125jphQV0NnM5nGFtcXXqoY3RpusTH_WcHPzH4S4l1PmB8Uu7ubZBftqFdxCLC5n-xT0fHcAY1"

以便我们可以像这样使用它

$(function () {
    $("#submit-list").click(function () {
        $.ajax({
            url: '@Url.Action("SortDataSourceLibraries")',
            data: { items: $(".sortable").sortable('toArray'), @Html.AntiForgeryTokenForAjaxPost() },
            type: 'post',
            traditional: true
        });
    });
});

看起来它能够正常工作!

0
0 Comments

您错误地指定了contentTypeapplication/json

这是一个可能工作的示例。

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(string someValue)
    {
        return Json(new { someValue = someValue });
    }
}

视图:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}
    Click me to send an AJAX request to a controller action
    decorated with the [ValidateAntiForgeryToken] attribute

0