include antiforgerytoken in ajax post ASP.NET MVC

后端 未结 11 2281
感动是毒
感动是毒 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条回答
  •  遇见更好的自我
    2020-11-22 14:42

    Another (less javascriptish) approach, that I did, goes something like this:

    First, an Html helper

    public static MvcHtmlString AntiForgeryTokenForAjaxPost(this HtmlHelper helper)
    {
        var antiForgeryInputTag = helper.AntiForgeryToken().ToString();
        // Above gets the following: 
        var removedStart = antiForgeryInputTag.Replace(@"", "");
        if (antiForgeryInputTag == removedStart || removedStart == tokenValue)
            throw new InvalidOperationException("Oops! The Html.AntiForgeryToken() method seems to return something I did not expect.");
        return new MvcHtmlString(string.Format(@"{0}:""{1}""", "__RequestVerificationToken", tokenValue));
    }
    

    that will return a string

    __RequestVerificationToken:"P5g2D8vRyE3aBn7qQKfVVVAsQc853s-naENvpUAPZLipuw0pa_ffBf9cINzFgIRPwsf7Ykjt46ttJy5ox5r3mzpqvmgNYdnKc1125jphQV0NnM5nGFtcXXqoY3RpusTH_WcHPzH4S4l1PmB8Uu7ubZBftqFdxCLC5n-xT0fHcAY1"
    

    so we can use it like this

    $(function () {
        $("#submit-list").click(function () {
            $.ajax({
                url: '@Url.Action("SortDataSourceLibraries")',
                data: { items: $(".sortable").sortable('toArray'), @Html.AntiForgeryTokenForAjaxPost() },
                type: 'post',
                traditional: true
            });
        });
    });
    

    And it seems to work!

提交回复
热议问题