Create an action filter that inherits HandleErrorAttribute, as shown in the following example. Then you can check the request and handle the error.
public class AntiForgeryHandleErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext context) { if (context.Exception is HttpAntiForgeryException) { var url = string.Empty; if (!context.HttpContext.User.Identity.IsAuthenticated) { var requestContext = new RequestContext(context.HttpContext, context.RouteData); url = RouteTable.Routes.GetVirtualPath(requestContext, new RouteValueDictionary(new {Controller = "User", action = "Login"})).VirtualPath; } else { context.HttpContext.Response.StatusCode = 200; context.ExceptionHandled = true; url = GetRedirectUrl(context); } context.HttpContext.Response.Redirect(url, true); } else { base.OnException(context); } } private string GetRedirectUrl(ExceptionContext context) { try { var requestContext = new RequestContext(context.HttpContext, context.RouteData); var url = RouteTable.Routes.GetVirtualPath(requestContext, new RouteValueDictionary(new { Controller = "User", action = "AlreadySignIn" })).VirtualPath; return url; } catch (Exception) { throw new NullReferenceException(); } } }
This is my example, remember that you must process your redirect sections, depending on your request and requirements.
Then login
[HttpPost] [AllowAnonymous] [AntiForgeryHandleError] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(UserLoginViewModel model, string returnUrl) {
Edited for comments
Use another controller / action like AlreadySignIn ()
Controller code
public ActionResult AlreadySignIn() { return View(); }
View razor
@using Microsoft.AspNet.Identity @{ ViewBag.Title = "Switch Accounts"; Layout = "~/Views/Shared/_LayoutLoginRegister.cshtml"; } <div class="col-md-12"> <div class="block-flat text-center" style="padding: 20px; margin-bottom: 0; padding-bottom: 0;"> <i class="glyphicon glyphicon-user"></i> <br /> <label style="padding-bottom: 10px; padding-top: 10px">You're already signed in as <strong>@User.Identity.Name</strong></label> <label style="padding-bottom: 5px; padding-top: 5px">@Html.ActionLink("Remain signed in with this account.", "Login", "User", routeValues: null, htmlAttributes: new { id = "loginLink" })</label> <label style="padding-bottom: 5px; padding-top: 2px">@Html.ActionLink("Click here to sign out and sign with a different account", "LogOff", "User", routeValues: null, htmlAttributes: new { id = "loginLink" })</label> </div> </div>
Hope this helps.
DSR
source share