如何将路线数据从ActionFilterAttribute传递到操作方法?

时间:2019-01-02 21:07:43

标签: c# asp.net-core-mvc

如果会话已过期,我将使用ActionFilterAttribute将用户路由到登录视图,如下所示。

现在,我想保留原始请求中的路线数据,以便我可以在登录后将用户路由回到该视图。

如何将原始路线数据发送到Login操作方法?

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();
}

1 个答案:

答案 0 :(得分:1)

要成功登录后重新定向到上一个操作,您需要提供登录操作的返回URL,并将其值设置在OnActionExecuting中。

  1. 使用参数Login更改如下的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
                }));
            }
        }
    }