使用 $.ajax 发布 JSON 数据时如何提供 AntiForgeryToken? [英] How can I supply an AntiForgeryToken when posting JSON data using $.ajax?
问题描述
我使用的代码如下:
首先,我将使用控制器操作的正确值填充一个数组变量.
First I will fill an array variable with the correct values for the controller action.
使用下面的代码,我认为只需将以下行添加到 JavaScript 代码中就应该非常简单:
Using the code below I think it should be very straightforward by just adding the following line to the JavaScript code:
data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
<%= Html.AntiForgeryToken() %>
在它的正确位置,并且动作有一个 [ValidateAntiForgeryToken]
The <%= Html.AntiForgeryToken() %>
is at its right place, and the action has a [ValidateAntiForgeryToken]
但我的控制器操作一直说:无效的伪造令牌"
But my controller action keeps saying: "Invalid forgery token"
我在这里做错了什么?
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(); }
});
}
推荐答案
自 MVC 4 以来,您不需要 ValidationHttpRequestWrapper 解决方案.根据此 链接.
You don't need the ValidationHttpRequestWrapper solution since MVC 4. According to this link.
- 将令牌放在标题中.
- 创建过滤器.
- 将属性放在您的方法上.
这是我的解决方案:
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);
}
这篇关于使用 $.ajax 发布 JSON 数据时如何提供 AntiForgeryToken?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!