Enable Antiforgery Token with ASP.NET Core and JQuery

后端 未结 5 2126
鱼传尺愫
鱼传尺愫 2020-12-15 06:40

I am using JQuery with ASP.NET Core 1.0.1 and I have the Ajax call:

$(\"#send-message\").on(\"submit\", function (event) {
  event.preventDefault();
  var $f         


        
5条回答
  •  無奈伤痛
    2020-12-15 07:12

    mode777's answer just needs a small addition to make this work (I tried it):

    $(document).ajaxSend(function(e, xhr, options) {
        if (options.type.toUpperCase() == "POST") {
            var token = $form.find("input[name='af_token']").val();
            xhr.setRequestHeader("RequestVerificationToken", token);
        }
    });
    

    Actually, if you also submit using Ajax, you don't need to use a form at all. Put this in your _layout:

      @Html.AntiForgeryToken() 
    

    Then you pickup the token by adding this to your javascript:

    $(document)
       .ajaxSend(function (event, jqxhr, settings) {
            if (settings.type.toUpperCase() != "POST") return;
            jqxhr.setRequestHeader('RequestVerificationToken', $(".AntiForge" + " input").val())
    })
    

    The @HtmlAntiForgeryToken generates a hidden input field with the antiforgery token, the same as when using a form. The code above finds it using the class selector to select the span, then gets the input field inside that to collect the token and add it as a header.

提交回复
热议问题