Search code examples
ajaxasp.net-mvcantiforgerytoken

ASP.NET MVC AJAX POST ValidateAntiForgeryToken


With my code i get a internal Server error:

@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>

Controller:

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

If i remove [ValidateAntiForgeryToken] everything works fine, but i lose the sercurity. How can i fix the internal server error?

I see in fiddler SyntaxView 2 requests: /Manage/Like {"profileId":13,"__RequestVerificationToken":"jH2ofYlcTiHl8lixW_ANEHOg5KgwRh5Xl43lQfGkDFh55jX-x5cmz4RfPtbDfu92oQsTM7zsop83ldfbxMdIIELYZ0kfByFcXjUp-5mwyKZcQzjXP2gy6qW0iQOtLsqaDjFSzoxnyqM2MD42CbItzw2"}

/Manage __RequestVerificationToken=MNiKOJHZg7BGaTNccOjrR2Obf_nPhKfcwIPZVBUl53G368n5euzB4y1htH47VKg3V3mHfxkjYZDz6iPepQ7jpeXGARtlj6vV74B8zQbp4by9JR4Rcz4sHANm3WHb6WAXaLcsnFvWJth_8c98XKda5w2


Solution

  • Taking this from a sim. question here 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
     }); 
    }