关于角色的一般建议
我这样做的方法是创建一个自定义主体并在其中存储额外的必需信息。在您的示例中,这至少包括用户的角色。这样您就可以避免对用户存储(可能是 SQL 数据库)进行大量额外的访问。
看看我的这个问题,其中我给出了我成功使用的代码:基本控制器 ASP.NET MVC 3 中的自定义主体是否效率极低? https://stackoverflow.com/questions/8263845/is-this-custom-principal-in-base-controller-asp-net-mvc-3-terribly-inefficient
请注意,我将自定义主体存储在缓存中而不是会话中(只是对会话劫持感到偏执)。
我喜欢这种方法,因为它非常可扩展。例如,我后来对此进行了扩展,以在用户通过 Facebook 登录时公开 Facebook 凭据。
请记住,如果您正在缓存数据,则需要记住在数据更改时更新它!
回答你的问题
只是补充一下,在您的具体情况下,您可能应该将这些额外信息存储在ViewModel
然后你的观点会这样说:
@if(ShowReports) { <li id="ReportTab">@Html.ActionLink("Reports", "Index", "Reports")</li> }
@if(ShowDashboard) { <li id="DashboardTab">@Html.ActionLink("Dashboard", "Dashboard", "Admin")</li> }
@if(ShowAdmin { <li id="AdminTab">@Html.ActionLink("Admin", "Index", "Admin")</li> }
ViewModel 代码如下所示:
public bool ShowReports {get;set;}
public bool ShowDashboard {get;set;}
public bool ShowAdmin {get;set;}
public void SetViewModel()
{
if (User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.IsInRole("Reporters"))
{
ShowReports = true;
}
if (HttpContext.Current.User.IsInRole("Administrators"))
{
ShowDashboard = true;
ShowAdmin = true;
}
}
}
我实际上倾向于更进一步并创建一个ReportsLink
in my ViewModel
如果用户被授权,则将其设置为包含链接;如果未授权,则将其设置为空字符串。然后视图只是说:
@Model.ReportsLink
@Model.DashboardLink
@Model.AdminLink
在这种情况下,ViewModel 的相关部分可能如下所示:
ReportLink = new MvcHtmlString(HtmlHelper.GenerateLink(HttpContext.Current.Request.RequestContext, System.Web.Routing.RouteTable.Routes, "linktext", "routename", "actionname", "controllername", null, null));