【问题标题】:Unable to render Html MvcSiteMap Nodes based on User Types无法根据用户类型呈现 Html MvcSiteMap 节点
【发布时间】:2016-04-07 03:48:20
【问题描述】:

我有两种用户类型-
-管理员
-访客
如果用户类型是“访问者”,则 Sub1 节点将不会出现在菜单中。但下面的代码无法隐藏/删除特定节点。
我的站点地图如下所示:

<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"]="!*";  }  
}}

【问题讨论】:

    标签: asp.net-mvc-sitemap


    【解决方案1】:

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

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

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

    这假设您已经设置了一个实现 IPrincipalIIdentitysecurity framework(其中 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 部分。

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 2011-03-29
      • 2019-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 2021-08-10
      • 1970-01-01
      相关资源
      最近更新 更多