在MVC3或MVC4中的這種行爲是按設計的,但如上所述,它是非常不利於用戶的,但是在生產中,這個問題需要優雅地解決,應用程序需要處理這種奇怪的情況。此問題的解決方案是創建一個應用於登錄帖子的過濾器,以驗證用戶是否已登錄並將其帶到正確的頁面,否則它們將保留在登錄頁面上。
下面是過濾器的代碼屬性
/// <summary>
/// Handle Antiforgery token exception and redirect to customer area if the user is Authenticated
/// </summary>
public class RedirectOnError : HandleErrorAttribute
{
/// <summary>
/// Override the on exception method and check if the user is authenticated and redirect the user
/// to the customer service index otherwise continue with the base implamentation
/// </summary>
/// <param name="filterContext">Current Exception Context of the request</param>
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception is HttpAntiForgeryException && filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// Set response code back to normal
filterContext.HttpContext.Response.StatusCode = 200;
// Handle the exception
filterContext.ExceptionHandled = true;
UrlHelper urlH = new UrlHelper(filterContext.HttpContext.Request.RequestContext);
// Create a new request context
RequestContext rc = new RequestContext(filterContext.HttpContext, filterContext.RouteData);
// Create a new return url
string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { Controller = "CustomerArea", action = "Index" })).VirtualPath;
// Check if there is a request url
if (filterContext.HttpContext.Request.Params["ReturnUrl"] != null && urlH.IsLocalUrl(filterContext.HttpContext.Request.Params["ReturnUrl"]))
{
url = filterContext.HttpContext.Request.Params["ReturnUrl"];
}
// Redirect the user back to the customer service index page
filterContext.HttpContext.Response.Redirect(url, true);
}
else
{
// Continue to the base
base.OnException(filterContext);
}
}
}
這是使用
我離開了你另一個答案的例子 - 我應該已經回答了我的問題! – 2013-09-03 16:28:38