User.IsInRole始终返回真正的ASP.NET IDENTITY

时间:2015-09-03 11:40:40

标签: asp.net-mvc asp.net-identity

我通过仅为管理员角色中的用户返回列表项来尝试对我的_layourpartial文件进行基本自定义

<ul class="nav navbar-nav navbar-right">
    @if (User.IsInRole("admin"))
    {
        <li>@Html.ActionLink("Dashboard", "Dashboard", "Home")</li>
    }
    <li>
        @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
    </li>

</ul>

问题在于,当我从admin角色中删除用户时,User.IsInRole仍然返回true。

我试图删除cookie,注销/登录,重启iis express,......

没有任何作用!

1 个答案:

答案 0 :(得分:2)

在Identity中,当前用户角色存储为声明,User.IsInRole()检查应用声明而非实际角色。要从当前用户中删除角色,请执行以下操作:

var identity = (User.Identity as ClaimsIdentity);
var adminClaim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role && c.Value == "admin");
if(adminClaim!=null)
    identity.RemoveClaim(adminClaim);

或者您可以通过以下代码检查当前用户的实际角色而不是已分配的声明:

HttpContext.Current.GetOwinContext()
    .GetUserManager<ApplicationUserManager>()
    .IsInRole(User.Identity.GetUserId(), "admin");