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

后端 未结 1 650
野性不改
野性不改 2020-12-18 14:54

I have the following method in controller

[HttpPost]
    [Authorize(Roles =\"Klient\")]
    [ValidateAntiForgeryToken]
    public ActionResult GetAvaiableHou         


        
相关标签:
1条回答
  • 2020-12-18 15:46

    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

    0 讨论(0)
提交回复
热议问题