使用$ .ajax发布JSON数据时,如何提供AntiForgeryToken?

我正在使用下面这篇文章的代码:


首先,我将使用控制器操作的正确值填充数组变量。


使用下面的代码,我认为只需将以下行添加到JavaScript代码中,应该非常简单:


data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();

该<%= Html.AntiForgeryToken() %>是在其正确的位置,动作有[ValidateAntiForgeryToken]


但是我的控制器动作一直在说:“无效的伪造令牌”


我在这里做错了什么?


data["fiscalyear"] = fiscalyear;

data["subgeography"] = $(list).parent().find('input[name=subGeography]').val();

data["territories"] = new Array();


$(items).each(function() {

    data["territories"].push($(this).find('input[name=territory]').val());

});


    if (url != null) {

        $.ajax(

        {

            dataType: 'JSON',

            contentType: 'application/json; charset=utf-8',

            url: url,

            type: 'POST',

            context: document.body,

            data: JSON.stringify(data),

            success: function() { refresh(); }

        });

    }


慕雪6442864
浏览 602回答 3
3回答

波斯汪

你不需要因为MVC 4. ValidationHttpRequestWrapper解决方案根据这个链接。将令牌放在标题中。创建一个过滤器。将属性放在您的方法上。这是我的解决方案:var token = $('input[name="__RequestVerificationToken"]').val();var headers = {};headers['__RequestVerificationToken'] = token;$.ajax({&nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; url: '/MyTestMethod',&nbsp; &nbsp; contentType: 'application/json; charset=utf-8',&nbsp; &nbsp; headers: headers,&nbsp; &nbsp; data: JSON.stringify({&nbsp; &nbsp; &nbsp; &nbsp; Test: 'test'&nbsp; &nbsp; }),&nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; success: function () {},&nbsp; &nbsp; error: function (xhr) {}});[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter{&nbsp; &nbsp; public void OnAuthorization(AuthorizationContext filterContext)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (filterContext == null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new ArgumentNullException("filterContext");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; var httpContext = filterContext.HttpContext;&nbsp; &nbsp; &nbsp; &nbsp; var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];&nbsp; &nbsp; &nbsp; &nbsp; AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);&nbsp; &nbsp; }}[HttpPost][AllowAnonymous][ValidateJsonAntiForgeryToken]public async Task<JsonResult> MyTestMethod(string Test){&nbsp; &nbsp; return Json(true);}

Smart猫小萌

出问题的是,应该处理此请求并用[ValidateAntiForgeryToken]期望标记的控制器动作期望__RequestVerificationToken与该请求一起被称为POST 的参数。您正在使用的参数中没有POST,JSON.stringify(data)它会将表单转换为JSON表示形式,因此会引发异常。所以我可以在这里看到两个可能的解决方案:数字1:用于x-www-form-urlencoded代替JSON发送您的请求参数:data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();data["fiscalyear"] = fiscalyear;// ... other data if necessary$.ajax({&nbsp; &nbsp; url: url,&nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; context: document.body,&nbsp; &nbsp; data: data,&nbsp; &nbsp; success: function() { refresh(); }});数字2:将请求分为两个参数:data["fiscalyear"] = fiscalyear;// ... other data if necessaryvar token = $('[name=__RequestVerificationToken]').val();$.ajax({&nbsp; &nbsp; url: url,&nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; context: document.body,&nbsp; &nbsp; data: { __RequestVerificationToken: token, jsonRequest: JSON.stringify(data) },&nbsp; &nbsp; success: function() { refresh(); }});因此,在所有情况下,您都需要发布该__RequestVerificationToken值。
打开App,查看更多内容
随时随地看视频慕课网APP