include antiforgerytoken in ajax post ASP.NET MVC

后端 未结 11 2367
感动是毒
感动是毒 2020-11-22 14:00

I am having trouble with the AntiForgeryToken with ajax. I\'m using ASP.NET MVC 3. I tried the solution in jQuery Ajax calls and the Html.AntiForgeryToken(). Using that solu

11条回答
  •  不知归路
    2020-11-22 14:26

    In Asp.Net MVC when you use @Html.AntiForgeryToken() Razor creates a hidden input field with name __RequestVerificationToken to store tokens. If you want to write an AJAX implementation you have to fetch this token yourself and pass it as a parameter to the server so it can be validated.

    Step 1: Get the token

    var token = $('input[name="`__RequestVerificationToken`"]').val();
    

    Step 2: Pass the token in the AJAX call

    function registerStudent() {
    
    var student = {     
        "FirstName": $('#fName').val(),
        "LastName": $('#lName').val(),
        "Email": $('#email').val(),
        "Phone": $('#phone').val(),
    };
    
    $.ajax({
        url: '/Student/RegisterStudent',
        type: 'POST',
        data: { 
         __RequestVerificationToken:token,
         student: student,
            },
        dataType: 'JSON',
        contentType:'application/x-www-form-urlencoded; charset=utf-8',
        success: function (response) {
            if (response.result == "Success") {
                alert('Student Registered Succesfully!')
    
            }
        },
        error: function (x,h,r) {
            alert('Something went wrong')
          }
    })
    };
    

    Note: The content type should be 'application/x-www-form-urlencoded; charset=utf-8'

    I have uploaded the project on Github; you can download and try it.

    https://github.com/lambda2016/AjaxValidateAntiForgeryToken

提交回复
热议问题