ValidateAntiForgeryToken in Ajax request with AspNet Core MVC

前端 未结 3 1252
囚心锁ツ
囚心锁ツ 2021-02-14 00:18

I have been trying to recreate an Ajax version of the ValidateAntiForgeryToken - there are many blog posts on how to do this for previous versions of MVC, but with the latest MV

3条回答
  •  被撕碎了的回忆
    2021-02-14 00:48

    I had similar issue. I don't know if any changes are coming regarding this in .NET but, at the time, I added the following lines to ConfigureServices method in Startup.cs, before the line services.AddMvc(), in order to validate the AntiForgeryToken sent via Ajax:

    services.AddAntiforgery(options =>
    {
        options.CookieName = "yourChosenCookieName"; 
        options.HeaderName = "RequestVerificationToken";
    });
    

    The AJAX call would be something like the following:

    var token = $('input[type=hidden][name=__RequestVerificationToken]', document).val();
    
    var request = $.ajax({
        data: { 'yourField': 'yourValue' },
        ...
        headers: { 'RequestVerificationToken': token }
    });   
    

    Then, just use the native attribute [ValidadeAntiForgeryToken] in your Actions.

提交回复
热议问题