我有不同角色的用户。我想根据用户的角色提供受限制的 View 。我的代码中有一些检查角色的东西:
bool isAdmin = UserManager.IsInRole(currentUser.Id,"admin");
bool isEmployee = UserManager.IsInRole(currentUser.Id,"employee");
要使上述代码正常工作,我需要实例化 currentUser。换句话说,我需要捕获当前登录用户的信息。我尝试了类似 var user = User.Identity.GetUserId();
和许多其他但找不到工作代码。我将不胜感激任何帮助。谢谢!
更新:
这是我的完整方法代码。在我检查上面的例子之前,你们可能都想看看。
public ActionResult Index()
{
var user = User.Identity.GetUserId();
bool isAdmin = UserManager.IsInRole(user, "admin");
bool isEmployee = UserManager.IsInRole(user, "employee");
if (isAdmin)
{
return View(db.Customers.ToList());
}
else
{
var restricted = db.Customers.Where(c => c.FirstName == "John");
return View(restricted);
}
}
最佳答案
[Authorize]
属性应在所需的受限 actionController 方法中实现。示例如下。
[Authorize(Roles="Admin")]
public ActionResult Index()
{
return View();
}
此 Controller 方法仅限于具有管理员角色的用户。此外,相同的 Action Controller 方法可以使用不同的授权标签包含两次。
关于c# - 用户登录后缓存用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22179496/