检查您的 cookie 并确保您看到 requestVerificationToken cookie 设置正确。我之前遇到过这个问题,网站的 cookie 都设置为仅 SSL,我试图在本地通过常规 HTTP 运行它,所以 cookie 从未被接受,因为它是通过不安全的通道传输的。
对我来说,这意味着将 system.web/httpCookies 下 web.config 中的一行更改为 requireSSL="false"... 但如果这不是您所看到的,我仍然会查看可能会弄乱的东西您在系统中的 cookie(例如会话重置、在某处手动清除 cookie 等)。如果您在控制器方法上正确设置了验证属性,并且仍然得到此属性,则可能是由于修改或删除了该 cookie 造成的!
编辑:另外,如果您在控制器上而不是仅在 POST 方法上有这个,这就是为什么......这仅适用于向服务器发送 POST。
这是一个简单的自定义版本,您可以将其应用于将自动验证所有 POST 操作方法的表单:
/// <summary>
/// Custom Implementation of the Validate Anti Forgery Token Attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CustomValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
/// <summary>
/// The ValidateAntiForgeryTokenAttribute.
/// </summary>
private readonly ValidateAntiForgeryTokenAttribute _validator;
/// <summary>
/// The AcceptVerbsAttribute.
/// </summary>
private readonly AcceptVerbsAttribute _verbs;
/// <summary>
/// Initializes a new instance of the <see cref="CustomValidateAntiForgeryTokenAttribute"/> class.
/// </summary>
/// <param name="verbs">The verbs.</param>
public CustomValidateAntiForgeryTokenAttribute(HttpVerbs verbs) : this(verbs, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CustomValidateAntiForgeryTokenAttribute"/> class.
/// </summary>
/// <param name="verbs">The verbs.</param>
/// <param name="salt">The salt.</param>
public CustomValidateAntiForgeryTokenAttribute(HttpVerbs verbs, string salt)
{
_verbs = new AcceptVerbsAttribute(verbs);
_validator = new ValidateAntiForgeryTokenAttribute
{
Salt = salt
};
}
/// <summary>
/// Called when authorization is required.
/// </summary>
/// <param name="filterContext">The filter context.</param>
public void OnAuthorization(AuthorizationContext filterContext)
{
var httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride();
var found = false;
foreach (var verb in _verbs.Verbs)
{
if (verb.Equals(httpMethodOverride, StringComparison.OrdinalIgnoreCase))
{
found = true;
}
}
if (found && !filterContext.RequestContext.RouteData.Values["action"].ToString().StartsWith("Json"))
{
_validator.OnAuthorization(filterContext);
}
}
}
然后,您可以将以下内容添加到所有控制器中,或者如果您覆盖并继承自一个控制器,则可以添加到基本控制器中:
[CustomValidateAntiForgeryToken(HttpVerbs.Post)]