include antiforgerytoken in ajax post ASP.NET MVC

后端 未结 11 2365
感动是毒
感动是毒 2020-11-22 14:00

I am having trouble with the AntiForgeryToken with ajax. I\'m using ASP.NET MVC 3. I tried the solution in jQuery Ajax calls and the Html.AntiForgeryToken(). Using that solu

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 14:31

    In Asp.Net Core you can request the token directly, as documented:

    @inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf    
    @functions{
        public string GetAntiXsrfRequestToken()
        {
            return Xsrf.GetAndStoreTokens(Context).RequestToken;
        }
    }
    

    And use it in javascript:

    function DoSomething(id) {
        $.post("/something/todo/"+id,
                   { "__RequestVerificationToken": '@GetAntiXsrfRequestToken()' });
    }
    

    You can add the recommended global filter, as documented:

    services.AddMvc(options =>
    {
        options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
    })
    

    Update

    The above solution works in scripts that are part of the .cshtml. If this is not the case then you can't use this directly. My solution was to use a hidden field to store the value first.

    My workaround, still using GetAntiXsrfRequestToken:

    When there is no form:

    
    

    The name attribute can be omitted since I use the id attribute.

    Each form includes this token. So instead of adding yet another copy of the same token in a hidden field, you can also search for an existing field by name. Please note: there can be multiple forms inside a document, so name is in that case not unique. Unlike an id attribute that should be unique.

    In the script, find by id:

    function DoSomething(id) {
        $.post("/something/todo/"+id,
           { "__RequestVerificationToken": $('#RequestVerificationToken').val() });
    }
    

    An alternative, without having to reference the token, is to submit the form with script.

    Sample form:

    The token is automatically added to the form as a hidden field:

    And submit in the script:

    function DoSomething() {
        $('#my_form').submit();
    }
    

    Or using a post method:

    function DoSomething() {
        var form = $('#my_form');
    
        $.post("/something/todo/create", form.serialize());
    }
    

提交回复
热议问题