2016-03-11 122 views
0

您好我有一个使用MVC 5身份角色的ASP MVC应用程序,为了简单起见,我有2个身份角色(“Admin”和“Staff”) 。角色管理员中的用户可以访问管理员面板,他们可以在其中创建其他用户,而员工角色中的用户只能访问员工视图。 我在将用户分配给角色并将[Authorize]应用于控制器方面没有问题。根据他们的身份角色重定向用户 - ASP MVC 4和5

我想在成功登录后将用户重定向到相对视图,因此如果用户处于管理员角色,get会自动重定向到管理面板或视图,并且员工页面中的用户重定向到人员视图。

我该如何在我的登录控制器中应用这个?谢谢

+0

您可以在成功登录后,根据角色简单地将用户重定向到相应的操作。这对你有用吗? – SamGhatak

+0

http://stackoverflow.com/questions/26526536/asp-net-mvc-5-identity-2-login-redirect-based-on-user-role/26527406#26527406 – tmg

回答

0

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

  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

这是一个有用的链接类似的问题http ://stackoverflow.com/questions/26526536/asp-net-mvc-5-identity-2-login-redirect-based-on-user-role LQ = 1 –

0
if(UserType.Admin) 
{ 
      return RedirectToAction("HomeAdmin","Admin") // Admin Home 
} 
else if(UserType.Staff) 
{ 
      return RedirectToAction("HomeStaff","Staff")//Staff Home 
} 

而且在动作方法

[Authorize]// Use this to authorize 
public ActionResult HomeStaff() 
{ 
} 
0

[这就是我如何解决它,我没有改变没有找到任何UserType或User.Role如上述解决方案所述]

1

如果您使用UserManager和SignInManager(作为每个默认模板):

[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); 
    } 
} 
相关问题