I am trying to pass an AntiForgery token in the header of an Ajax request. My JavaScript code looks like this:
var tokenadr = $('form[action="/ServiceRequests/CreateRequest"] input[name="__RequestVerificationToken"]').val();
var token = tokenadr;
var headers = {};
var headersadr = {};
headers['__RequestVerificationToken'] = token;
headersadr['__RequestVerificationToken'] = tokenadr;
$.ajax({
type: 'POST',
dataType: 'json',
headers: headersadr,
cache: false,
url: "/ServiceRequests/CreateRequest",
processData: false,
contentType: false,
data: formdata,
success: function (response, textStatus, jqXHR) {
window.location = "/ServiceRequests/Details/" + response.id;
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
},
})`
My form looks like this:
@using (Html.BeginForm("CreateRequest", "ServiceRequests", null, FormMethod.Post, new { enctype = "multipart/form-data", id = "requestForm" }))
{
@Html.AntiForgeryToken()
The problem is that in my shared views folder, I have a partial login view with a form like this:
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
So when I call my controller method using the Ajax code above, I get a server error. My request does go through if I delete the AntiForgery token from my Account LogOff form (the token values are different for each form). How can I resolve this without deleting my account logoff token?
Here is my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateRequest()
{
Here is what I have mainly been going by: How to make ajax request with anti-forgery token in mvc