开发者

Help with asp.net mvc authorization

Say you want to display a menu that has many elements... Some elements are exclusive to users with "administrator" role. I know how to restrict controllers methods using

开发者_开发问答
[Authorize(Roles = "Administrators")]

but I want to figure out a way to display a specific html thing depending on the user roles

example

<ul>
<li>Menu Item 1</li>
<% //if is admin%>
<li>Menu Item 2 (for admins only)</li>
</ul>

How do I do thiis?


<ul>
<li>Menu Item 1</li>
<% if(Roles.IsUserInRole("Administrators")) { %>
<li>Menu Item 2 (for admins only)</li>
<% } %>
</ul>


Two ways to do this. If you pass your list items into the View via ViewData then your action would look like this:

public ViewResult Menu() {
  var list = new string[]{ "Menu Item 1" };
  if(HttpContext.User.IsInRole("Administrators"))
    list.Add(Menu Item 2 (for admins only)");
  ViewData["MenuItems"] = list;
  return View();
}

Otherwise you could simply set a value in your ViewData to indicate to the view if the it should display admin values.

public ViewResult Menu() {
  ViewData["DisplayAdminItems"] = HttpContext.User.IsInRoles("Administrators");
}

You don't want to use the Authorize filter because you want to allow non-admins to access that action. I guess alternatively you can have two actions, one that is has the Authorize filter and one that doesn't. However that forces all links and redirects to those actions to decide which one to use.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜