登录MVC5时路由角色

时间:2015-08-24 09:43:32

标签: c# visual-studio-2013 asp.net-mvc-5 authorization roles

我是MVC的新手,我目前正在创建一个需要路由登录的Web应用程序。我有3个用户 - 管理员,配镜师和用户。登录后,我希望将管理员重定向到管理员页面,将配镜师重定向到配镜师页面,将用户重定向到主页。 启动后,我创建了角色。我已将用户注册到角色并且工作正常。我现在要做的是在登录时路由角色。

启动验证:

        // Creating new instance of Role Manager
        var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

        //Creating User role
        RoleManager.Create(new IdentityRole("User"));
        //Creating Admin role
        RoleManager.Create(new IdentityRole("Admin"));
        //Creating Optician role
        RoleManager.Create(new IdentityRole("Optician"));

帐户管理员:

    // GET: /Account/Login
    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                if(User.IsInRole("Admin")){
                    return RedirectToAction("Index", "Admin");
                }
                else if (User.IsInRole("Optician"))
                {
                    return RedirectToAction("Index","Optician");
                }
                else
                {   // if role is User
                    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.");
                return View(model);
        }
    }

路线配置:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

但是,当我以管理员或配镜师身份登录时,我被重定向到 - RedirectToLocal(returnUrl)而不是(&#34;索引&#34;,&#34;管理员&#34;)或(&#34;索引& #34;,&#34;配镜师&#34;)。为了这个问题的简单而提前道歉,但我不确定我的错误在哪里。如果if语句在POST登录中?任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

我找到了出错的地方。我需要创建一个重定向方法,因为用户尚未在登录阶段登录他们的角色。登录后,用户将被引导至重定向方法,该方法根据其角色重定向它们。

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl, ApplicationUser user)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }


        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToAction("RedirectLogin"); 
            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.");
                return View(model);
        }
    }

    public ActionResult RedirectLogin(string returnUrl)
    {
        if(User.IsInRole("Admin")){
                    return RedirectToAction("Index", "Admin");
                }
                else if (User.IsInRole("Optician"))
                {
                    return RedirectToAction("Index","Optician");
                }
                else
                {
                    return RedirectToLocal(returnUrl);
                }
    }