.Net Core ValidateAntiForgeryToken throwing web api 400 error

user8545750 picture user8545750 · Sep 13, 2017 · Viewed 8.5k times · Source

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.

Answer

Amir Reza picture Amir Reza · Sep 25, 2018

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