如果用户未登录 MVC,自定义登录页面将覆盖返回 URL



我有一个基于角色的自定义登陆

    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var theLoggedInEmail = model.Email;
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                var user = await UserManager.FindAsync(model.Email, model.Password);
                var roles = await UserManager.GetRolesAsync(user.Id);
                if (roles.Contains("user"))
                {
                    return RedirectToAction("Index", "Custom_dashboard", routeValues: new { id = User.Identity.GetUserId() });
                    //Send a mail to user to notify them of logging in
                }
                if (roles.Contains("Admin"))
                {
                    return RedirectToAction("Index", "Admin_dashboard", routeValues: new { id = User.Identity.GetUserId() });
                }
                else
                {
                    return RedirectToLocal(returnUrl);
                }
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt. Please try again with correct email and password");
                return View(model);
        }           
    }

另一个模块用于在用户登录时显示一些信息。

"视图"页

    @if ( (User.Identity.IsAuthenticated) && (User.IsInRole("Employer")) ) {
        [Information to be displayed...]
    }
    @if (User.Identity.IsAuthenticated == false)
    {
       <h4 class="text-center">
           @Html.ActionLink("Login", "Login", "Account", new { @returnUrl = ViewContext.HttpContext.Request.Url.PathAndQuery }, null)
       </h4>
    }

如果用户未登录,系统会将用户重定向到登录页面并对该用户进行身份验证,如果成功,系统将显示视图,但会显示自定义登录页面。

请问我如何让它工作

如果将

Login路由设置为您不想遵循的returnURL类型LoginreturnURL更改为重定向到路由(无查询字符串)。

然后returnURL将被清除,它应该按照您想要的方式工作

最新更新