ASP.NET MVC AJAX POST ValidateAntiForgeryToken

时间:2017-07-05 19:57:46

标签: ajax asp.net-mvc antiforgerytoken

使用我的代码我收到内部服务器错误:

@using (Html.BeginForm("", "Manage", FormMethod.Post, new { role = "form"}))
{
    @Html.AntiForgeryToken()
}
<script>
function Like(id) {
    var requestData = {
        profileId: id,
        __RequestVerificationToken: $('[name=__RequestVerificationToken]').val(),
    };

    $.ajax({
        url: '/Manage/Like',
        type: 'POST',
        data: JSON.stringify(requestData),
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        error: function (xhr) { alert('Error: ' + xhr.statusText); },
        success: function (result) {},
        async: true,
        processData: false
    });
}
</script>

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Like(string profileId)
{ ... }

如果我删除[ValidateAntiForgeryToken]一切正常,但我失去了安全性。如何修复内部服务器错误?

我在fiddler中看到了SyntaxView 2的请求: /管理/像 {&#34;简档&#34;:13,&#34; __ RequestVerificationToken&#34;:&#34; jH2ofYlcTiHl8lixW_ANEHOg5KgwRh5Xl43lQfGkDFh55jX-x5cmz4RfPtbDfu92oQsTM7zsop83ldfbxMdIIELYZ0kfByFcXjUp-5mwyKZcQzjXP2gy6qW0iQOtLsqaDjFSzoxnyqM2MD42CbItzw2&#34;}

/管理 __RequestVerificationToken = MNiKOJHZg7BGaTNccOjrR2Obf_nPhKfcwIPZVBUl53G368n5euzB4y1htH47VKg3V3mHfxkjYZDz6iPepQ7jpeXGARtlj6vV74B8zQbp4by9JR4Rcz4sHANm3WHb6WAXaLcsnFvWJth_8c98XKda5w2

1 个答案:

答案 0 :(得分:1)

从sim中取这个。问题include antiforgerytoken in ajax post ASP.NET MVC

function Like(id) {
 var form = $('form');
 var token = $('input[name="__RequestVerificationToken"]', form).val();
 $.ajax({
    url: '/Manage/Like',
    type: 'POST',
    data: { __RequestVerificationToken: token, profileID: id },
    error: function (xhr) { alert('Error: ' + xhr.statusText); },
    success: function (result) {},
    async: true,
    processData: false
 }); 
}