简体   繁体   中英

How to pass route data from an ActionFilterAttribute to an action method?

I'm routing users to a login-view if the session has expired, using an ActionFilterAttribute , like shown below.

Now, I want to keep the route data from the original request, so that I can route the user back to that view after logging in.

How can I send the original route data to the Login action method?

public class BaseController : Controller
{
    public int? BranchId {get => HttpContext.Session.GetInt32("BranchId") as int?;}
    public string Admin {get => HttpContext.Session.GetString("Admin") as string;}

    public BaseController() {}
}

public class AdminOrBranchesAccessAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        base.OnActionExecuting(context);

        if ((context.Controller as BaseController).Admin == null &&
            (context.Controller as BaseController).BranchId == null)
        {
            context.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "Home",
                action = "Login"
            }));
        }
    }
}

[AdminOrBranchesAccess]
public async Task<IActionResult> Details(int? id)
{
    // Some stuff going on
    return View();
}

For rediecting to previous action after login successfully, you need to provide return url for login action and set its value in OnActionExecuting .

  1. Change Login method like below with parameter returnUrl

     [HttpGet] [AllowAnonymous] public async Task<IActionResult> Login(string returnUrl = null) { // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); ViewData["ReturnUrl"] = returnUrl; return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: true); if (result.Succeeded) { _logger.LogInformation("User logged in."); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); return RedirectToAction(nameof(Lockout)); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } // If we got this far, something failed, redisplay form return View(model); } 
  2. AdminOrBranchesAccessAttribute

     public class AdminOrBranchesAccessAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context); if ((context.Controller as BaseController).Admin == null && (context.Controller as BaseController).BranchId == null) { context.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Login", returnUrl = context.HttpContext.Request.Path })); } } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM