I have ASP.NET MVC 5 Application using .Net 4.5.1. The application has several jQuery ajax post method that POST data to server. To prevent cross-site request forgery (XSRF) i have added the following in _layout.cshtml
@Html.AntiForgeryToken()
and also javascript which sends the token with all ajax POST in HttpHeader
$(document).ajaxSend(function (event, jqXHR, ajaxOptions) {
if (ajaxOptions.type === 'POST') {
jqXHR.setRequestHeader('__RequestVerificationToken', $('input[name="__RequestVerificationToken"]').val());
}
});
and then in controller action method i have
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Save(MyModel model)
{
//save and return json data
}
However ValidateAntiForgeryToken thorwing exception
The required anti-forgery form field "__RequestVerificationToken" is not present.
i verified that __RequestVerificationToken
is getting added to httpheader for every Ajax POST.
I have another application that was developed using ASP.NET Core and i have the same functionality there (Except the header name is RequestVerificationToken
instead of __RequestVerificationToken
) and its been working in ASP.NET Core.
Why the same is not working in ASP.NET MVC when token is included in header? Is there any difference ValidateAntiForgeryToken in ASP.NET Core vs ASP.NET MVC 5?