【问题标题】:ViewContext.HttpContext.User.IsInRole("Admin") is not workingViewContext.HttpContext.User.IsInRole("Admin") 不工作
【发布时间】:2017-07-25 01:24:13
【问题描述】:

我正在尝试隐藏链接,或者如果用户不是管理员,我将无法访问该页面。我可以在我的控制器中使用此代码来完成后者:

[AuthorizeRoles("Admin")]
public ActionResult Registration()
{
   return View();
}

当我尝试使用此代码隐藏链接时:

@if (!Context.User.Identity.Name.IsEmpty())
{
    <li id="dd_vehicle" class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">VEHICLE <b class="caret"></b></a>
    <ul class="dropdown-menu">
    @if (ViewContext.HttpContext.User.IsInRole("Admin"))
    {
        <li id="item_registration">
            @Html.ActionLink("Registration", "Registration", "Home")
        </li>
    }
}

链接被隐藏。但是当我以“管理员”身份登录时,链接仍然没有显示。

这就是我授权属性的方式:

public class AuthorizeRolesAttribute : AuthorizeAttribute
{
    private readonly string[] userAssignedRoles;

    public AuthorizeRolesAttribute(params string[] roles)
    {
        this.userAssignedRoles = roles;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool authorize = false;
        using (var db = new SMBI_DBEntities())
        {
            var um = new UserManager();
            foreach (var roles in userAssignedRoles)
            {
                authorize = um.IsUserInRole(httpContext.User.Identity.Name, roles);
                if (authorize)
                    return authorize;
            }
        }
            return authorize;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectResult("~/Home/UnAuthorized");
    }
}

这是在 LoginView 中:

[HttpPost]
public ActionResult Login(UserLoginView ulv, string returnUrl)
{
    if (ModelState.IsValid)
    {
        var um = new UserManager();
        var password = um.GetUserPassword(ulv.LoginName);

        if (string.IsNullOrEmpty(password))
        {
            ModelState.AddModelError("", "Login ID and Pasword do not match.");
        }
        else
        {
            if (ulv.Password.Equals(password))
            {
                FormsAuthentication.SetAuthCookie(ulv.LoginName, false);
                return RedirectToAction("Registration", "Home");
            }
            else
            {
                ModelState.AddModelError("","Password provided is incorrect.");
            }
        }
    }
    return View(ulv);
}

希望您能提供帮助。谢谢。

【问题讨论】:

  • AuthorizeAttribute 不适用于视图端;在这方面它变得有点复杂......网上有一些很好的资源可以在这方面提供帮助。

标签: asp.net-mvc


【解决方案1】:

您好,您可以尝试如下:

@if(Page.User.IsInRole("Admin"))
 {
        <li id="item_registration">
            @Html.ActionLink("Registration", "Registration", "Home")
        </li>
}

有用的链接:How to use Page.User.IsInRole

作为附加信息,如果需要,您还可以为将来的目的编写如下所示的帮助器

public static class PrincipalExtensions
{
    public static bool IsInAllRoles(this IPrincipal principal, params string[] roles)
    {
        return roles.All(r => principal.IsInRole(r));
    }

    public static bool IsInAnyRoles(this IPrincipal principal, params string[] roles)
    {
        return roles.Any(r => principal.IsInRole(r));
    }
}

现在您可以像这样调用这个扩展方法:

// user must be assign to all of the roles  
if(User.IsInAllRoles("Admin","Manager","YetOtherRole"))
{
    // do something
} 

// one of the roles sufficient
if(User.IsInAnyRoles("Admin","Manager","YetOtherRole"))
{
    // do something
} 

来源: https://stackoverflow.com/a/32385065/3397630

谢谢

【讨论】:

  • Karthik,我应该把“PrincipalExtensions”放在哪里?它应该在另一个班级吗?如何实施?
  • 我收到此错误:无法对指向“@if (Page.User.IsInRole("Admin"))”的空引用执行运行时绑定
  • yup "PrincipalExtensions" 是一个单独的类,一旦你写了你就会得到像 IsInAllRoles,IsInAnyRoles 这样的附加方法给用户对象。对于错误“无法在空引用上执行运行时绑定”可能还有其他原因,请检查此网址forums.asp.net/t/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-16
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-01
相关资源
最近更新 更多