[ASP.NET]Show Menu Items For Different Roles

In an ASP.NET site, some time we want to show a menu item for administrator only. For example, we want to display "edit" link for blogger owner. Below are steps to take action to achieve this feature:
1. Create a Web.sitemap file and add menu items to this file

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
    <siteMapNode url="" title=""  description="" roles="*">
        <siteMapNode url="~\Admin.aspx" title="Admin" roles="Manager" />
        <siteMapNode url="~\DebateTopics.aspx" title="DebateTopics"/>
    </siteMapNode>
</siteMap>


Note that I specify roles attribute for siteMap and siteMapNode element. so that only when a Manager log in to the system then Admin menu will display in the page.

2. Add siteMap node to web.config file, inside <system.web> element

 

 <siteMap enabled="true">
      <providers>
        <clear/>
        <add siteMapFile="Web.sitemap" 
             name="AspNetXmlSiteMapProvider" 
             type="System.Web.XmlSiteMapProvider" 
             securityTrimmingEnabled="true"/>
      </providers>
 </siteMap>

we need also configure authorization for the Admin.aspx page

<location path="Admin.aspx">
    <system.web>
      <authorization>
        <allow roles="Manager"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>


3. Add code to Site.master file

 

<asp:SiteMapDataSource runat="server" 
ID="siteMapDataSource" ShowStartingNode="false" />

 

 

<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" 
       
   EnableViewState="false" IncludeStyleBlock="false"
         
Orientation="Horizontal"
          DataSourceID="siteMapDataSource">

"Note: then, we can delete the <items> node from Site.Mater page“

 

Now, all done. When we open the page, we can only see the DebateTopics menu

After log in:

blog comments powered by Disqus