0

How can I execute a controller action in ASP.NET MVC4 sending the anti foreign key too?

My request is formed as follow code snippet:

var _antiForeignKey = dojoQuery('input[name="__RequestVerificationToken"]', dojo.byId('#__AjaxAntiForgeryForm'))[0].value;

xhr.post({
   url: 'Account/LogOff',
   handleAs: 'json',
   contentType: 'application/json',
   postData: '__RequestVerificationToken=' + _antiForeignKey 
});

And I receive an error from server with a html which contains the

The required anti-forgery form field "__RequestVerificationToken" is not present.

message as response. Obviously, the action in the controller is not executed.

I've seen this post: jQuery Ajax calls and the Html.AntiForgeryToken(), which answers my question but using jQuery.

Community
  • 1
  • 1
christiansr85
  • 867
  • 19
  • 40

1 Answers1

0

I have got to execute the controller action by using the previous code snippet but modifying the value of two parameters, 'handleAs' and 'contentType':

var _antiForeignKey = dojoQuery('input[name="__RequestVerificationToken"]', dojo.byId('#__AjaxAntiForgeryForm'))[0].value;

xhr.post({
   url: 'Account/LogOff',
   handleAs: 'text',
   contentType: 'application/x-www-form-urlencoded',
   postData: '__RequestVerificationToken=' + _antiForeignKey        
});

As you can see, I've changed the 'handleAs' property because we are not handling json data in the response, and the 'contentType' to specify we are sending other type of data as request's parameter.

christiansr85
  • 867
  • 19
  • 40