无法基于用户类型呈现Html MvcSiteMap节点

时间:2016-04-07 03:48:20

标签: asp.net-mvc-sitemap

我有两种用户类型 -
-admin
-Visitor
如果用户类型为“访客”,则菜单中不会显示Sub1节点。但以下代码无法隐藏/删除特定节点。
我的Sitemap看起来像:

<mvcSiteMapNode title="Home" controller="Home" action="Index">
<mvcSiteMapNode title="Site Map Test" controller="SitemapTest"action="Index" key="sitemaptestnode"> 
<mvcSiteMapNode title="Sub1" controller="SitemapTest" action="Sub1" key="Childsitemaptestnode1" visibility ="false"/>
<mvcSiteMapNode title="Sub2" controller="SitemapTest" action="Sub2" key="Childsitemaptestnode2"/>
<mvcSiteMapNode title="Sub3" controller="SitemapTest" action="Sub3" />
</mvcSiteMapNode>
</mvcSiteMapNode>

我从Layout.cshtml调用了

@Html.Action(“RenderMenu”,”Menu”);


Public void RenderMenu(){
var node = MvcSiteMapProvider.SiteMaps.Current.FindSiteMapNodeFromKey("Childsitemaptestnode1");
If (node.title =="Sub1"){
//Function to get the user type from database
String UserType=GetUserTypes();
If(UserType=="Visitor"){
//Hide Sub1 node from Menu
node.Attributes["visibility"]="!*";  }  
}}

1 个答案:

答案 0 :(得分:0)

处理此问题的最常用方法是使用基于组的安全性并使用AuthorizeAttribute

然而,在这个简单的场景中,你甚至不需要组。将AuthorizeAttribute添加到您的操作方法将自动拒绝任何未登录的用户。

    [Authorize]
    public ActionResult Sub1()
    {
        return View();
    }

这假设您已设置security framework来实现IPrincipalIIdentity(其中ASP.NET身份和成员身份都是如此)。您可以使用Visual Studio创建的默认模板之一获取其中一个选项的基本框架,并将相关位(AccountControllerManageController,相关视图和相关启动代码)复制到你的项目。

MvcSiteMapProvider中需要的所有内容都是enable security trimming

内部DI(web.config)

<appSettings>
    <add key="MvcSiteMapProvider_SecurityTrimmingEnabled" value="true"/>
</appSettings>

外部DI(MvcSiteMapProvider模块)

bool securityTrimmingEnabled = true; // Near the top of the module

这将使节点在用户无权访问时自动隐藏,AuthorizeAttribute将实际保护URL,以便用户无法直接在那里导航。

更改链接的可见性并不能保护任何内容,但如果这就是您想要的,那么您应该参考文档的visibility provider部分。

相关问题