If your stringifying the data and using contentType: 'application/json
, then add the token to the ajax headers, for example
var headers = { __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val() };
$.ajax({
headers: headers,
data: ... // remove the token from your existing implementation
....
});
and then you need to create a custom FilterAttribute
to read the value from the Headers
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ValidateHeaderAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
var httpContext = filterContext.HttpContext;
var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
}
}
and in your controller method, replace [ValidateAntiForgeryToken]
with [ValidateHeaderAntiForgeryToken]
However, it is not necessary to stringify the data, and you can use
var data = {
startDate: $("#startdate").val(),
endDate: $("#enddate").val(),
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
};
$.ajax({
data: data,
....
});
and remove the contentType
option so it uses the default 'application/x-www-form-urlencoded; charset=UTF-8'
You have not shown your form, assuming it contains @Html.AntiForgeryToken()
and @Html.TextBoxFor(m => m.startDate)
and @Html.TextBoxFor(m => m.endDate)
to that you generate form controls with name="startDate"
and name="endDate"
, then you can simply use
var data = $('form').serialize();
$.ajax({
data: data,
....
});
to serialize all your form controls including the token
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…