嗨,我有一个使用MVC5身份角色的ASP MVC应用程序,为了简单起见,我有两个身份角色("Admin“和"Staff")。角色管理员的用户可以访问管理面板,他们可以在其中创建其他用户,而员工角色的用户只能访问员工视图。我可以将用户分配给角色并将授权应用于控制器。
我想在成功登录后将用户重定向到他们的相关视图,所以如果用户是管理员角色,get的自动重定向到管理面板或视图,如果用户在员工页面重定向到员工视图。
如何在我的登录控制器中应用此功能?谢谢
发布于 2016-03-31 22:02:22
如果您在控制器中使用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);
}
}发布于 2016-03-11 18:26:20
您可以简单地将它们从您的登录操作方法重定向。所以伪代码如下所示。
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");
}注释只是为了给你一些想法,它可能在你的应用程序中有所不同
发布于 2016-03-11 18:28:26
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()
{
}https://stackoverflow.com/questions/35937186
复制相似问题