我已经将我们的MVC代码从版本2.0升级到了4.0。现在,我收到以下错误:“未提供所需的防伪令牌或该令牌无效。”
我在ValidateAntiForgeryTokenAttribute.cs中添加了以下代码:
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride();
if (!this.verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase))
{
return;
}
AntiForgeryDataSerializer antiForgeryDataSerializer = new AntiForgeryDataSerializer();
AntiForgeryData antiForgeryData = new AntiForgeryData();
string fieldName = antiForgeryData.GetAntiForgeryTokenName(null);
string cookieName = antiForgeryData.GetAntiForgeryTokenName(filterContext.HttpContext.Request.ApplicationPath);
HttpCookie cookie = filterContext.HttpContext.Request.Cookies[cookieName];
if (cookie == null || String.IsNullOrEmpty(cookie.Value))
{
throw CreateValidationException();
}
AntiForgeryData cookieToken = antiForgeryDataSerializer.Deserialize(cookie.Value);
//Rest of the code here//
}在"filterContext“中,cookie名称是"_RequestVerificationToken”,然后添加路径名。路径名以Base64编码并添加到AntiForgeryFieldName中,这就变成了"_RequestVerificationToken_Lw__“。当我们检查cookie是否存在时,很明显我们找不到它,我们得到了AntiForgery异常。但在这段代码的旧版本中,"filterContext“中的Cookie值是"_RequestVerificationToken_Lw__”,因此工作得很好。那么,这里的问题在哪里呢?它是与机器键相关的还是其他什么?
提前谢谢。
发布于 2017-07-19 01:54:21
视图中的@Html.AntiForgeryToken()调用会生成一个新的令牌,并以如下形式写入:
<form action="..." method="post">
<input name="__RequestVerificationToken" type="hidden"
value="J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP" />
<!-- Other fields. -->
</form>并将其写入cookie:
__RequestVerificationToken_Lw__=
J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP当以上表单提交时,它们都会被发送到服务器。
在服务器端,ValidateAntiForgeryToken属性用于指定控制器或操作来验证它们:
[HttpPost]
[ValidateAntiForgeryToken()]
public ActionResult Action(/* ... */)
{
// ...
}您所需要做的就是在视图中调用AntiForgeryToken并在控制器操作上指定"ValidateAntiForgeryToken“属性。
https://stackoverflow.com/questions/45170480
复制相似问题