Enable Antiforgery Token with ASP.NET Core and JQuery

后端 未结 5 2143
鱼传尺愫
鱼传尺愫 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 06:59

    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());
    })
    

提交回复
热议问题