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.
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly