ASPNET CORE Ajax Post results in 400 Bad Request ASPNET CORE Ajax Post results in 400 Bad Request ajax ajax

ASPNET CORE Ajax Post results in 400 Bad Request


Looks like you have AutoValidateAntiforgeryTokenAttribute filter applied globally. That means when an HTTP Post action method is called(normal or ajax), the framework will check the submitted request data and if it does not find a valid anti forgery token(RequestVerificationToken header), it will be considered a bad request and a 400 response will be sent back.

To fix this problem, you can explicitly read the value of __RequestVerificationToken hidden input (generated by the form tag helper) and send that in your ajax request headers.

var t = $("input[name='__RequestVerificationToken']").val();$.ajax({    url: "/test/TestCall",    type: 'Post',    headers:    {        "RequestVerificationToken": t    },    success: function (result) {        alert("Success");        var res = result;    },    error: function (jqXHR) {        var z = 3;    },    complete: function (jqXHR, status) {        var x = 10;    }});

You can make the code more robust by injecting the IAntiforgery implementation to the view/page and using the GetAndStoreTokens method.

Add this to your view

@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf@functions{public string GetAntiXsrfRequestToken(){    return Xsrf.GetAndStoreTokens(Context).RequestToken;}}

and call this GetAntiXsrfRequestToken function to get the value in your javascript ( which is inside the view file)

headers:{    "RequestVerificationToken": '@GetAntiXsrfRequestToken()'},


Try to specify the header with X-XSRF-TOKEN.

For ABP Intercept XMLHttpRequest.

Since all libraries use JavaScript's native AJAX object, XMLHttpRequest, you can define a simple interceptor to add the token to the header:

(function (send) {    XMLHttpRequest.prototype.send = function (data) {        this.setRequestHeader(abp.security.antiForgery.tokenHeaderName, abp.security.antiForgery.getToken());        return send.call(this, data);    };})(XMLHttpRequest.prototype.send);

For abp.security.antiForgery.tokenHeaderName, its default value is X-XSRF-TOKEN


In Core -- make sure your <form> tag includes method="post".

The method is required to invoke the form tag helper which automatically adds the antiforgery token to the form. (I accidentally left off the method and didn't notice because I was ajax-posting it.)