[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"/>

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">
        <add siteMapFile="Web.sitemap" 

we need also configure authorization for the Admin.aspx page

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

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"

"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