我已将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异常。 但是在这段代码的旧版本中,Cookie值在" filterContext"来自" _RequestVerificationToken_Lw __"因此,工作正常。 那么,这里的问题在哪里?它与Machine Keys或其他东西有关吗?
提前致谢。
答案 0 :(得分:0)
视图中的@ 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并指定&#34; ValidateAntiForgeryToken&#34;控制器动作的属性。