The required anti-forgery form field “__RequestVerificationToken” is not present in ajax call

本小妞迷上赌 提交于 2019-11-29 17:36:45

If your stringifying the data and using contentType: 'application/json, then add the token to the ajax headers, for example

var headers = { __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() };

$.ajax({
    headers: headers,
    data: ... // remove the token from your existing implementation
    ....
});

and then you need to create a custom FilterAttribute to read the value from the Headers

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ValidateHeaderAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        var httpContext = filterContext.HttpContext;
        var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
        AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
    }
}

and in your controller method, replace [ValidateAntiForgeryToken] with [ValidateHeaderAntiForgeryToken]

However, it is not necessary to stringify the data, and you can use

var data = {
    startDate: $("#startdate").val(),
    endDate: $("#enddate").val(),
    __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
};

$.ajax({
    data: data,
    ....
});

and remove the contentType option so it uses the default 'application/x-www-form-urlencoded; charset=UTF-8'

You have not shown your form, assuming it contains @Html.AntiForgeryToken() and @Html.TextBoxFor(m => m.startDate) and @Html.TextBoxFor(m => m.endDate) to that you generate form controls with name="startDate" and name="endDate", then you can simply use

var data = $('form').serialize();

$.ajax({
    data: data,
    ....
});

to serialize all your form controls including the token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!