How to include anti-forgery token in ajax request in ASP.NET MVC?


When I am posting Form using jQuery Ajax in my ASP.NET Zero template, I am getting this error "Invalid anti-forgery token" or "The required anti-forgery form field \"__RequestVerificationToken\" is not present."

How can I Include in it in my AJAX Request in ASP.NET MVC, here is my current jQuery code

     var myData = JSON.stringify("MyDataHere");

     $.ajax({
        type: 'POST',
        url: saveUrl,
        data: myData ,
        success: function () {
            console.log("Saved")
        },
        dataType: 'json',
        contentType: "application/json; charset=utf-8"
    });

I think it is not related to C# Controller code, so not including it.


Asked by:- Vinnu
0
: 6667 At:- 11/27/2018 2:44:59 PM
ASP.NET C# anti-forgery token in ajax







1 Answers
profileImage Answered by:- jaya

First Create a C# Helper function in a Class, so you can use it for other AJAX request also

public static MvcHtmlString AntiForgeryTokenForAjaxPost(this HtmlHelper helper)
{
    var antiForgeryInputTag = helper.AntiForgeryToken().ToString();
    // Above gets the following: <input name="__RequestVerificationToken" type="hidden" value="PnQE7R0MIBBAzC7SqtVvwrJpGbRvPgzWHo5dSyoSaZoabRjf9pCyzjujYBU_qKDJmwIOiPRDwBV1TNVdXFVgzAvN9_l2yt9-nf4Owif0qIDz7WRAmydVPIm6_pmJAI--wvvFQO7g0VvoFArFtAR2v6Ch1wmXCZ89v0-lNOGZLZc1" />
    var removedStart = antiForgeryInputTag.Replace(@"<input name=""__RequestVerificationToken"" type=""hidden"" value=""", "");
    var tokenValue = removedStart.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));
}

It will return us a string with AnitforgeryToken value, which we can include in AJAX headers or simply include it in AJAX data (here i Will add it in AJAX data, as we are already getting formatted string like "__RequestVerificationToken:"TokenValue...."")

And use it like below


    $("#submitData").click(function () {
        $.ajax({
            type: 'post',
            url: '/URLHere',
            data: { uname: username,
                    pass: password ,
                    @Html.AntiForgeryTokenForAjaxPost()
                   },
           
        });
    });

OR

Simply generate a AnitForgeryToken in Javascript, and send it with Data

<script type="text/javascript">
    function getGeneratedToken() {
        var token = '@Html.AntiForgeryToken()';
        token = $(token).val();
        return token;
   }
</script>

now while sending AJAX request, add it with data as we did above

$.ajax({
    type: "POST",
    url: "/URLHere",
    data: {
        __RequestVerificationToken: gettoken(),
        uname: username,
        pass: password 
    },
    dataType: 'json',
    contentType: 'application/x-www-form-urlencoded; charset=utf-8'
    
});

The Second approach is basically done using Javascript only, and token is generated on Page load by using Razor Syntax @Html.AntiForgeryToken(), also note the content-type of the above method, it should work if you are posting JSON on server.

1
At:- 11/30/2018 10:05:39 AM
Excellent answer, thanks 0
By : Vinnu - at :- 12/5/2018 8:58:13 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use