如何根据用户在ASP.NET MVC中的角色隐藏链接?

时间:2014-02-18 22:15:00

标签: asp.net-mvc roleprovider

我试图找出如何根据用户角色隐藏链接。因此,当用户登录并发送到主页时,如果用户不是管理员,我希望隐藏在视图中的以下链接(查看用户):

<li>@Html.ActionLink("Users", "Index", "User")</li>

这是我控制器中的Index

[Authorize(Users = "Admin")]
public ActionResult Index()
{
    var user = db.User.Include(u => u.UserRole);
    return View(user.ToList());
}

有关如何实现这一目标的任何建议?

4 个答案:

答案 0 :(得分:3)

这就是我通常在我看来实施的方式。

@if (Request.IsAuthenticated && User.IsInRole("Admin"))
{
<li>@Html.ActionLink("Users", "Index", "User")</li>
}

答案 1 :(得分:1)

不确定这是否仍适用于最新的MVC框架,但我过去曾使用过这个:

public static MvcHtmlString AuthorizedActionLink<TController>
(
    this HtmlHelper helper,
    Expression<Action<TController>> action,
    string linkText, object htmlAttributes
)
where TController : Controller
{
    var routeValuesFromExpression = ExpressionHelper.GetRouteValuesFromExpression(action);

    return 
        helper.IsAuthorized(action)
            ? helper.RouteLink(linkText, routeValuesFromExpression, new RouteValueDictionary(htmlAttributes))
            : null;
}

public static bool IsAuthorized<TController>(this HtmlHelper helper, Expression<Action<TController>> action)
{
    var call = action.Body as MethodCallExpression;

    if (call == null) return false;

    var authorizeAttributes = call.GetAttributes<IAuthorizationFilter>();
    if (authorizeAttributes.Length == 0) return true;

    var controllerContext = helper.ViewContext.Controller.ControllerContext;
    var controllerDescriptor = new ReflectedControllerDescriptor(typeof(TController));
    var actionDescriptor = new ReflectedActionDescriptor(call.Method, call.Method.Name, controllerDescriptor);

    return authorizeAttributes.All(a => IsAuthorized(a, controllerContext, actionDescriptor));
}

答案 2 :(得分:0)

试一试:

    @if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin")){           
        <a href="~/Admin/Admin">Admin</a>    
    }

答案 3 :(得分:0)

@if(expression)
{
    code
}

在.cshtml文件中