【发布时间】:2021-06-09 21:34:03
【问题描述】:
我试图从我的 js 文件将防伪令牌传递给 MVC 控制器中的 HTTPPost 方法。我收到以下错误:
“防伪令牌验证失败:所需的防伪cookie“__RequestVerificationToken”不存在。”
当我尝试调试 js 代码并查看时,我在“antiForgeryToken”变量中看到了令牌。但不确定发生了什么。有人可以告诉我我在做什么错吗?这是我的 js 文件中的代码:
options.data = function (find) {
var antiForgeryToken = $("#forgeryToken").val();
fetch('/Options/Students/StudentScore',
{
method: 'POST',
body: JSON.stringify({
find: find,
querystringParams: querystringParams
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
"RequestVerificationToken": antiForgeryToken
}
})
.then(function (response) { return response.json() })
.then(function (response) {
var mapped = _.map(response.Results,
function(i) {
return {
DisplayValue: i.text
}
});
return mapped;
})
.catch(function(err) {
debugger;
});
}
这是我的操作方法
[System.Web.Mvc.HttpPost]
[ValidateAntiForgeryTokenAttribute]
public async Task<ActionResult> StudentScore([FromBody] StudentValues request)
{
//Implementation
return JsonNet(sometestval, JsonRequestBehavior.AllowGet);
}
这是我的防伪课
[AttributeUsage(AttributeTargets.Method)]
public class ValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
try
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
ValidateRequestHeader(filterContext.HttpContext.Request);
}
else
{
AntiForgery.Validate();
}
}
catch(Exception e)
{
throws exception;
}
}
private static void ValidateRequestHeader(HttpRequestBase request)
{
var cookieToken = string.Empty;
var formToken = string.Empty;
var tokenValue = request.Headers["RequestVerificationToken"];
if (!string.IsNullOrEmpty(tokenValue))
{
var tokens = tokenValue.Split(':');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken);
}
}
【问题讨论】:
-
正如
Willy David Jr所说,你需要从$('input[name="__RequestVerificationToken"]')获取数据。如果你没有输入名字是__RequestVerificationToken,你需要将@Html.AntiForgeryToken()或<form method="post"></form>添加到您的视图中。
标签: c# asp.net-mvc asp.net-core razor antiforgerytoken