首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据用户的身份角色重定向用户- ASP MVC 4和5

根据用户的身份角色重定向用户- ASP MVC 4和5
EN

Stack Overflow用户
提问于 2016-03-11 18:03:15
回答 4查看 4K关注 0票数 0

嗨,我有一个使用MVC5身份角色的ASP MVC应用程序,为了简单起见,我有两个身份角色("Admin“和"Staff")。角色管理员的用户可以访问管理面板,他们可以在其中创建其他用户,而员工角色的用户只能访问员工视图。我可以将用户分配给角色并将授权应用于控制器。

我想在成功登录后将用户重定向到他们的相关视图,所以如果用户是管理员角色,get的自动重定向到管理面板或视图,如果用户在员工页面重定向到员工视图。

如何在我的登录控制器中应用此功能?谢谢

EN

回答 4

Stack Overflow用户

发布于 2016-03-31 22:02:22

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

代码语言:javascript
复制
[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);
    }
}
票数 4
EN

Stack Overflow用户

发布于 2016-03-11 18:26:20

您可以简单地将它们从您的登录操作方法重定向。所以伪代码如下所示。

代码语言:javascript
复制
            if (User.Role == "Admin")
            {
                //send him to Admin controller and index action
                return RedirectToAction("ActionName","Controllername"); 
            }
            else if (User.Role == "Staff")
            {
                //send him to staff controller and index action
                return RedirectToAction("ActionName","Controllername"); 
            }
            else
            { 
               // if neither role show default public page
               return RedirectToAction("ActionName","Controllername");
            }

注释只是为了给你一些想法,它可能在你的应用程序中有所不同

票数 0
EN

Stack Overflow用户

发布于 2016-03-11 18:28:26

代码语言:javascript
复制
if(UserType.Admin)
{
            return RedirectToAction("HomeAdmin","Admin") // Admin Home
}
else if(UserType.Staff)
{
            return RedirectToAction("HomeStaff","Staff")//Staff Home
}

在你的动作方法中

代码语言:javascript
复制
[Authorize]// Use this to authorize
public ActionResult HomeStaff()
{
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35937186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档