You might have seen below error while doing ajax post to MVC action that validates AntiForgeryToken.
ASP.net MVC ValidateAntiForgeryToken does not handle passing RVToken in ajax requests by default.
ex: Below token sent in header won't be accepted at Controller level in MVC:
I found a better solution that works perfectly fine for all POST requests. Just implement the custom MVC Authorize attribute as shown below code:
ASP.net MVC ValidateAntiForgeryToken does not handle passing RVToken in ajax requests by default.
ex: Below token sent in header won't be accepted at Controller level in MVC:
__RequestVerificationToken = $('[name=__RequestVerificationToken]').val()
I found a better solution that works perfectly fine for all POST requests. Just implement the custom MVC Authorize attribute as shown below code:
[AttributeUsage(AttributeTargets.Class, AttributeTargets.Method)] public class MyValidateAntiForgeryToken : AuthorizeAttribute { public override void OnAuthorization( AuthorizationContext filterContext ) { var request = filterContext.HttpContext.Request; if (request.HttpMethod == WebRequestMethods.Http.Post) { if (request.IsAjaxRequest()) { var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName]; var cookieValue = antiForgeryCookie != null ? antiForgeryCookie.Value : null; AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]); } else { new ValidateAntiForgeryTokenAttribute() .OnAuthorization(filterContext); } } } }You can add this attribute on either a post action method or on the controller class.
Put the below code in your _Layout.cshtml. This will handle the responsibility of sending AntiForgeryToken on all ajax post requests.
$(document).ready(function () { $.ajaxSetup({ 'beforeSend': function (xhr) { securityToken = $('[name=__RequestVerificationToken]').val(); xhr.setRequestHeader("__RequestVerificationToken", securityToken); }}); });
Happy Coding!!!