What they are showing in Anti-CSRF and AJAX section of the tutorial is a non-standard token validation method. In this example you would not use [ValidateAntiForgeryToken]
, but rather run the validation manually. Firstly you inject additional header in ajax call:
headers: {
'RequestVerificationToken': '@TokenHeaderValue()'
},
and then read and validate token from the header in your action:
[HttpPost]
public ActionResult Return(DeviceUsage dev)
{
ValidateRequestHeader(Request);
//process action
}
void ValidateRequestHeader(HttpRequestBase request)
{
string cookieToken = "";
string formToken = "";
if (request.Headers["RequestVerificationToken"] != null)
{
string[] tokens = request.Headers["RequestVerificationToken"].Split(':');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken);
}
Notice that ValidateRequestHeader()
reads the header set earlier by jQuery call. Also, I've amended the method slightly to accept HttpRequestBase
.
Tip: To avoid adding ValidateRequestHeader()
to every controller that responds to ajax calls, add it to your base controller if you have any, and derive all controllers from the base. Or even better create your own [ValidateAntiForgeryAjaxToken]
attribute.