我知道有很多关于这个问题的主题,但我已经尝试了几种解决方案,但无法使其发挥作用。
因此,我正在尝试在视图中验证当前登录的用户角色。正如StackOverflow中关于此主题的主要部分所述,我只需要做:
@User.IsInRole("Admin")
不幸的是,即使使用"角色"在AspNetUsers表中,当前登录用户的列填充了" Admin"。
我也尝试过以下方法,但它说" UserManager在当前环境中不存在"。
<p>@UserManager.GetRoles(userId)</p>
我的一个疑问是我在注册时没有正确设置用户的角色。我的AspNetRoles表已正确填充,但AspNetUserRoles表为空。
如何解决此问题以查找我的应用程序出了什么问题,以便我可以使用@ User.IsInRole(...)指令?
提前感谢您的帮助。
答案 0 :(得分:1)
这对我来说很好。 只需确保您已在数据库中植入了角色,并且已为注册的用户分配了角色,这应该可以正常工作。
{
<a asp-action="StudentDashboard" asp-controller="Home">Dashboard</a>
}
else
if (User.IsInRole("College"))
{
<a asp-action="CollegeDashboard" asp-controller="Home">Dashboard</a>
}
else
if (User.IsInRole("Manager"))
{
<a asp-action="AdminDashboard" asp-controller="Home">Dashboard</a>
}
else
if (User.IsInRole("Admin"))
{
<a asp-action="AdminDashboard" asp-controller="Home">Dashboard</a>
}```
答案 1 :(得分:0)
您是否尝试在视图页面顶部添加以下内容:
@if(Roles.IsUserInRole(User.Identity.GetUserName(), "Admin"))
可替换地:
<script type="text/javascript" src="filename.php"></script>
答案 2 :(得分:0)
我认为你没有写或者你写错了,但是在global.asax下面的代码是错误的:
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
//let us take out the username now
string Email = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string roles = string.Empty;
using (DatabaseContext entities = new DatabaseContext())
{
var user = entities.TblUsers.Where(u => u.Email == Email).FirstOrDefault().IDRole;
//here
roles = entities.TblRoles.Where(x => x.IDRole == user).FirstOrDefault().RoleName;
}
//let us extract the roles from our own custom cookie
// and here
//Let us set the Pricipal with our user specific details
e.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(Email, "Forms"), roles.Split(';'));
}
catch
{
//somehting went wrong
}
}
}
}