3 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
你不需要因?yàn)镸VC 4. ValidationHttpRequestWrapper解決方案根據(jù)這個(gè)鏈接。
將令牌放在標(biāo)題中。
創(chuàng)建一個(gè)過濾器。
將屬性放在您的方法上。
這是我的解決方案:
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
$.ajax({
type: 'POST',
url: '/MyTestMethod',
contentType: 'application/json; charset=utf-8',
headers: headers,
data: JSON.stringify({
Test: 'test'
}),
dataType: "json",
success: function () {},
error: function (xhr) {}
});
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class ValidateJsonAntiForgeryTokenAttribute : 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"]);
}
}
[HttpPost]
[AllowAnonymous]
[ValidateJsonAntiForgeryToken]
public async Task<JsonResult> MyTestMethod(string Test)
{
return Json(true);
}

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
出問題的是,應(yīng)該處理此請(qǐng)求并用[ValidateAntiForgeryToken]期望標(biāo)記的控制器動(dòng)作期望__RequestVerificationToken與該請(qǐng)求一起被稱為POST 的參數(shù)。
您正在使用的參數(shù)中沒有POST,JSON.stringify(data)它會(huì)將表單轉(zhuǎn)換為JSON表示形式,因此會(huì)引發(fā)異常。
所以我可以在這里看到兩個(gè)可能的解決方案:
數(shù)字1:用于x-www-form-urlencoded代替JSON發(fā)送您的請(qǐng)求參數(shù):
data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
data["fiscalyear"] = fiscalyear;
// ... other data if necessary
$.ajax({
url: url,
type: 'POST',
context: document.body,
data: data,
success: function() { refresh(); }
});
數(shù)字2:將請(qǐng)求分為兩個(gè)參數(shù):
data["fiscalyear"] = fiscalyear;
// ... other data if necessary
var token = $('[name=__RequestVerificationToken]').val();
$.ajax({
url: url,
type: 'POST',
context: document.body,
data: { __RequestVerificationToken: token, jsonRequest: JSON.stringify(data) },
success: function() { refresh(); }
});
因此,在所有情況下,您都需要發(fā)布該__RequestVerificationToken值。
- 3 回答
- 0 關(guān)注
- 628 瀏覽
添加回答
舉報(bào)