這是真的,該ValidateAntiForgeryToken
類是密封的,但它不是火箭科學推出我們自己:
public class MyValidateAntiForgeryTokenAttribute: FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
System.Web.Helpers.AntiForgery.Validate();
}
}
當然現在所有剩下的在我們的實現是從filterContext增加一些檢查是否當前的動作裝飾有一些自定義ExcludeFromAntiForgeryValidation
屬性,而不是調用Validate
方法。
東西線沿線的:
public class MyValidateAntiForgeryTokenAttribute: FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
bool shouldValidate = !filterContext
.ActionDescriptor
.GetCustomAttributes(typeof(ExcludeFromAntiForgeryValidationAttribute), true)
.Any();
if (shouldValidate)
{
System.Web.Helpers.AntiForgery.Validate();
}
}
}
,然後只寫一個自定義屬性:
[AttributeUsage(AttributeTargets.Method)]
public class ExcludeFromAntiForgeryValidationAttribute : Attribute
{
}
與您要排除防僞驗證,你會用它來裝飾你的控制器操作:
[HttpPost]
[ExcludeFromAntiForgeryValidation]
public ActionResult Index(MyViewModel model)
{
...
}