.Net Core ValidateAntiForgeryToken throwing web api 400 error

10,694

Solution 1

You need to send the AntiForgery token on every request where it's being validated either as a cookie or as a http header.

Refer to the documentation here. They have a section on how to configure angular js to do it.

Solution 2

You must send the AntiForgery token on every request

 var arr = { City: 'Tehran', Age: 25 };
    $.ajax({
        url: "@Url.Action("SaveAccess", "Access")",
        type: 'POST',
        data: JSON.stringify(arr),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        beforeSend: function (request) {
            request.setRequestHeader("RequestVerificationToken", $("[name='__RequestVerificationToken']").val());
        },
        success: function (msg) {
            alert(msg);
        }
    });
Share:
10,694

Related videos on Youtube

Admin
Author by

Admin

Updated on July 13, 2022

Comments

  • Admin
    Admin almost 2 years

    Visual Studio 2017 with Web Api using .net Core 1.1 I'm using, but I am getting a 400 Bad Request Error.

    Error Occurs in every way:

    1. Angular http
    2. Fiddler
    3. Postman
    4. SoapUI
    5. Swagger

    ASP.NET Web API “400 Bad Request” on POST Request

    [HttpPut]
    //[ValidateAntiForgeryToken]
    public IActionResult Put([FromBody]VeteranInteraction sessionTracker)
    { //.... } 
    

    Why is this happening ?

    ValidateAntiForgeryToken is the problem , if I comment it out it works.

  • JSON
    JSON over 6 years
    I applied the exact implementation and can't get it to work