經過一段時間的調查,我想我找到了一些方法來擺脫用戶的這個錯誤。它並不完美,但至少沒有顯示錯誤頁面:
我創建基於HandleErrorAttribute
過濾器:
[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",
Justification = "This attribute is AllowMultiple = true and users might want to override behavior.")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class LoginAntiforgeryHandleErrorAttribute : FilterAttribute, IExceptionFilter
{
#region Implemented Interfaces
#region IExceptionFilter
/// <summary>
/// </summary>
/// <param name="filterContext">
/// The filter context.
/// </param>
/// <exception cref="ArgumentNullException">
/// </exception>
public virtual void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (filterContext.IsChildAction)
{
return;
}
// If custom errors are disabled, we need to let the normal ASP.NET exception handler
// execute so that the user can see useful debugging information.
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
Exception exception = filterContext.Exception;
// If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
// ignore it.
if (new HttpException(null, exception).GetHttpCode() != 500)
{
return;
}
// check if antiforgery
if (!(exception is HttpAntiForgeryException))
{
return;
}
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "Index" },
{ "controller", "Home" }
});
filterContext.ExceptionHandled = true;
}
#endregion
#endregion
}
然後我應用這個過濾器登錄POST操作:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[LoginAntiforgeryHandleError]
public ActionResult Login(Login model, string returnUrl)
{
主要思路此解決方案的目的是將防僞造異常重定向到主索引操作。如果用戶仍然不會未經身份驗證,則會顯示登錄頁面如果用戶已經通過身份驗證,它將顯示索引頁面。
UPDATE 1 此解決方案存在一個潛在的問題。如果有人使用不同的憑據登錄,那麼應該添加額外的登錄運行時 - 註銷以前的用戶並登錄新的用戶。這種情況不會被處理。
這對我很好。我不需要它做任何幻想。只是不要扔黃色的屏幕。 – hal9000