首先,这是一个非常糟糕的设计。 MVC 的重点是在控制器中分离方法。如果您希望两个方法具有相同的行为,我建议修改您的控制器,使其具有一个 GET 和一个 POST,它们各自在控制器的其他地方调用相同的方法。
但是您可以编写一个 Validation 属性来完成您想要的。
基于此source code,您可以将Validation 属性中的OnAuthorization 方法编辑为:
public void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request.HttpMethod;
if (request != "GET")
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
ValidateAction();
}
}
现在检查请求是否为GET,在这种情况下它会跳过验证。完整的 Attribute 类是:
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Web.Helpers;
namespace System.Web.Mvc
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class ValidateAntiForgeryTokenAttribute2 : FilterAttribute, IAuthorizationFilter
{
private string _salt;
public ValidateAntiForgeryTokenAttribute2()
: this(AntiForgery.Validate)
{
}
internal ValidateAntiForgeryTokenAttribute2(Action validateAction)
{
Debug.Assert(validateAction != null);
ValidateAction = validateAction;
}
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "AdditionalDataProvider", Justification = "API name.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "AntiForgeryConfig", Justification = "API name.")]
[Obsolete("The 'Salt' property is deprecated. To specify custom data to be embedded within the token, use the static AntiForgeryConfig.AdditionalDataProvider property.", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public string Salt
{
get { return _salt; }
set
{
if (!String.IsNullOrEmpty(value))
{
throw new NotSupportedException("The 'Salt' property is deprecated. To specify custom data to be embedded within the token, use the static AntiForgeryConfig.AdditionalDataProvider property.");
}
_salt = value;
}
}
internal Action ValidateAction { get; private set; }
public void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request.HttpMethod;
if (request != "GET")
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
ValidateAction();
}
}
}
}