0

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);
            }
        }
    }

}
MapleStory
  • 628
  • 3
  • 11
  • 22
  • Maybe [this](http://stackoverflow.com/questions/10093053/add-header-in-ajax-request-with-jquery) would help you? – SᴇM Nov 01 '16 at 08:52
  • @SeM I saw this post and try it as it said ,still not working.I use console.log to check the token if generated ,it is ok.and the popup window is another page in the same website. – MapleStory Nov 01 '16 at 08:55

0 Answers0