如果会话已过期,我将使用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();
}
答案 0 :(得分:1)
要成功登录后重新定向到上一个操作,您需要提供登录操作的返回URL,并将其值设置在OnActionExecuting
中。
使用参数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);
}
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
}));
}
}
}