I am trying to add custom header in ajax but failed in bootstrap modal dialog,if I put below code in the normal page but the popup page ,it can work fine. the code looks like these:
var token = $('@Html.AntiForgeryToken()').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
console.log(token);
$.ajax({
type: 'POST',
url: '@Url.Action("SignGainPoint")',
cache: false,
data: null,
//beforeSend: function (request) {
// request.setRequestHeader("__RequestVerificationToken", token);
//},
headers:headers,
success: function (e) {
if (e.IsSuccess) {
$(".today").children("span").html(e.data);
}
else {
$(".today").children("span").html(0);
}
},
error: function () {
alert("Error");
}
});
})
and background code,the request.Headers["__RequestVerificationToken"] is null in asp.net mvc code.
public class MyValidateAntiForgeryToken : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
if (request.HttpMethod== WebRequestMethods.Http.Post)
{
if (request.IsAjaxRequest())
{
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = antiForgeryCookie != null
? antiForgeryCookie.Value : null;
AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
}
else
{
new ValidateAntiForgeryTokenAttribute()
.OnAuthorization(filterContext);
}
}
}
}