Hành vi này trong MVC3 hoặc MVC4 được thiết kế tuy nhiên không thân thiện với người dùng như đã giải thích ở trên, tuy nhiên trong quá trình sản xuất, vấn đề này cần được giải quyết một cách duyên dáng và ứng dụng cần xử lý tình huống kỳ lạ này. Giải pháp cho vấn đề này là tạo bộ lọc được áp dụng cho bài đăng đăng nhập để xác minh xem người dùng có đăng nhập hay không và đưa họ đến đúng trang nếu không họ sẽ vẫn ở trang đăng nhập.
Dưới đây là đoạn code cho bộ lọc thuộc tính
/// <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);
}
}
}
Đây là ví dụ về việc sử dụng
[HttpPost]
**[RedirectOnError]**
[ValidateAntiForgeryToken]
public ActionResult LogOn(LogOnViewModel model, UserSessionState session, string returnUrl)
{
.....
}
Tôi đã để lại cho bạn câu trả lời khác - tôi nên đã trả lời câu hỏi của riêng tôi! –