根据用户的身份角色重定向用户-ASP MVC 4和5 [英] Redirect users according to their Identity Role - ASP MVC 4 and 5

查看:99
本文介绍了根据用户的身份角色重定向用户-ASP MVC 4和5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有一个使用MVC 5身份角色的ASP MVC应用程序,为简单起见,我有2个身份角色(管理员"和工作人员").角色管理员中的用户可以访问管理面板,在此他们可以创建其他用户,而职员角色中的用户只能访问职员视图.在为用户分配角色并将[Authorise]应用于Controller方面,我没有问题.

Hi I have an ASP MVC Application that using the MVC 5 Identity Roles, for the sake of simplicity I have 2 Identity Roles ("Admin" and "Staff"). Users in Role Admin can access the Admin Panel where they can create another users, and Users in Staff Role can only access Staff View. I have no problem in assigning users to roles and apply [Authorise] to Controllers.

我想在成功登录后将用户"用户重定向到其相对的视图,因此,如果用户是管理员角色,则自动将获取"用户重定向到管理面板或视图,并且如果在工作人员"页面中的用户已重定向到工作人员视图".

I want to redirect Users users to their relative Views after success log ins, so if a user is in Admin role, get's automatically redirected to admin panel or view and if a user in staff page redirected to staff view.

如何在我的登录控制器中应用它?谢谢

How do I apply this in my Login Controller? Thanks

推荐答案

如果您在Controller中使用UserManager和SignInManager(根据默认模板):

If you're using UserManager and SignInManager (as per the default template) in your Controller:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SignIn(SignInViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: true);
    switch (result)
    {
        case SignInStatus.Success:
            ApplicationUser user = await UserManager.FindAsync(model.Email, model.Password);
            // Redirect to User landing page on SignIn, according to Role
            if ((UserManager.IsInRole(user.Id, "User")))
            {
                return RedirectToAction("Index", "User");
            }
            if ((UserManager.IsInRole(user.Id, "Administrator")))
            {
                return RedirectToAction("Index", "Administrator");
            }
            return View(model);
        // etc below - code to taste
        case SignInStatus.LockedOut:
            return View(model);
        case SignInStatus.RequiresVerification:
            return View(model);
        case SignInStatus.Failure:
        default:
            return View(model);
    }
}

这篇关于根据用户的身份角色重定向用户-ASP MVC 4和5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆