Basharat Hussain
Basharat Hussain

Reputation: 237

Asp.Net Core Unobtrusive Ajax throwing 400 error on live server

My Every form is of type

 <form id="addform" asp-area="Admin" asp-controller="Departments" asp-action="Add" data-ajax="true" data-ajax-method="post" data-ajax-success="onSuccess" data-ajax-failure="onFailure" data-ajax-begin="onBegin">
</form>

I have also appended RequestVerificationToken on every ajaxSend request

$(document).ajaxSend(function (e, xhr, options) {
    debugger;
    if (options.type.toUpperCase() == "POST") {
        var token = $("input[name='__RequestVerificationToken']").val();
        xhr.setRequestHeader("__RequestVerificationToken", token);
    }
});

My controllers are like this

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Add(DepartmentViewModel departmentViewModel)
{
     return View();
}

Now, it is working fine locally but not working correctly on the live server. Some requests are working fine and after few request it return 400 bad request error.

I have tried many things but all in vain. I need this security otherwise I would have skipped the same

Upvotes: 0

Views: 122

Answers (1)

Mike Brind
Mike Brind

Reputation: 30065

The header name should be RequestVerificationToken without the leading underscores. The version with the underscores is the name you should use if you are posting it as a form value. You can configure this to something else:

https://www.learnrazorpages.com/security/request-verification#configuration

Upvotes: 0

Related Questions