我已将MVC代码从2.0版升级到4.0版。 现在,我收到以下错误: “所需的防伪令牌未提供或无效。”AntiForgeryToken无效
我添加在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__”,因此工作正常。 那么,这里的问题在哪里?它与机器钥匙还是其他什么有关?
在此先感谢。
我不完全确定我明白你在这里做什么。防伪是内置于MVC。你不需要你自己的属性;只需在您的视图中使用控制器操作中的内置'ValidationAntiForgeryToken'属性和'@ Html.AntiForgeryToken()'。 –