SiteMapProvider Class


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Provides a common base class for all site map data providers, and a way for developers to implement custom site map data providers that can be used with the ASP.NET site map infrastructure as persistent stores for SiteMap objects.

Namespace:   System.Web
Assembly:  System.Web (in System.Web.dll)

Public MustInherit Class SiteMapProvider
	Inherits ProviderBase


Initializes a new instance of the SiteMapProvider class.


Gets the SiteMapNode object that represents the currently requested page.


Gets a brief, friendly description suitable for display in administrative tools or other user interfaces (UIs).(Inherited from ProviderBase.)


Gets or sets a Boolean value indicating whether localized values of SiteMapNode attributes are returned.


Gets the friendly name used to refer to the provider during configuration.(Inherited from ProviderBase.)


Gets or sets the parent SiteMapProvider object of the current provider.


Get or sets the resource key that is used for localizing SiteMapNode attributes.


Gets the root SiteMapNode object of the site map data that the current provider represents.


Gets the root SiteMapProvider object in the current provider hierarchy.


Gets a Boolean value indicating whether a site map provider filters site map nodes based on a user's role.


Adds a SiteMapNode object to the node collection that is maintained by the site map provider.

System_CAPS_protmethodAddNode(SiteMapNode, SiteMapNode)

Adds a SiteMapNode object to the node collection that is maintained by the site map provider and specifies the parent SiteMapNode object.


Determines whether the specified object is equal to the current object.(Inherited from Object.)


Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)


Retrieves a SiteMapNode object that represents the currently requested page using the specified HttpContext object.


When overridden in a derived class, retrieves a SiteMapNode object that represents the page at the specified URL.


Retrieves a SiteMapNode object based on a specified key.


When overridden in a derived class, retrieves the child nodes of a specific SiteMapNode.


Provides an optimized lookup method for site map providers when retrieving the node for the currently requested page and fetching the parent and ancestor site map nodes for the current page.

System_CAPS_pubmethodGetCurrentNodeAndHintNeighborhoodNodes(Int32, Int32)

Provides an optimized lookup method for site map providers when retrieving the node for the currently requested page and fetching the site map nodes in the proximity of the current node.


Serves as the default hash function. (Inherited from Object.)


When overridden in a derived class, retrieves the parent node of a specific SiteMapNode object.

System_CAPS_pubmethodGetParentNodeRelativeToCurrentNodeAndHintDownFromParent(Int32, Int32)

Provides an optimized lookup method for site map providers when retrieving an ancestor node for the currently requested page and fetching the descendant nodes for the ancestor.

System_CAPS_pubmethodGetParentNodeRelativeToNodeAndHintDownFromParent(SiteMapNode, Int32, Int32)

Provides an optimized lookup method for site map providers when retrieving an ancestor node for the specified SiteMapNode object and fetching its child nodes.


When overridden in a derived class, retrieves the root node of all the nodes that are currently managed by the current provider.


Retrieves the root node of all the nodes that are currently managed by the specified site map provider.


Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodHintAncestorNodes(SiteMapNode, Int32)

Provides a method that site map providers can override to perform an optimized retrieval of one or more levels of parent and ancestor nodes, relative to the specified SiteMapNode object.

System_CAPS_pubmethodHintNeighborhoodNodes(SiteMapNode, Int32, Int32)

Provides a method that site map providers can override to perform an optimized retrieval of nodes found in the proximity of the specified node.

System_CAPS_pubmethodInitialize(String, NameValueCollection)

Initializes the SiteMapProvider implementation, including any resources that are needed to load site map data from persistent storage.(Overrides ProviderBase.Initialize(String, NameValueCollection).)

System_CAPS_pubmethodIsAccessibleToUser(HttpContext, SiteMapNode)

Retrieves a Boolean value indicating whether the specified SiteMapNode object can be viewed by the user in the specified context.


Creates a shallow copy of the current Object.(Inherited from Object.)


Removes the specified SiteMapNode object from the node collection that is maintained by the site map provider.


Raises the SiteMapResolve event.


Returns a string that represents the current object.(Inherited from Object.)


Occurs when the CurrentNode property is called.

The StaticSiteMapProvider and XmlSiteMapProvider classes represent the default implementations of the abstract SiteMapProvider class. The XmlSiteMapProvider uses an XML file named Web.sitemap to store site map data. For more information on about the Web.sitemap file, see ASP.NET Site Maps.

The SiteMapProvider class supports the concept of a site map provider hierarchy, by declaring the RootProvider and ParentProvider properties. A SiteMapProvider can be a child or parent of another provider. This enables scenarios where different content areas of a site are owned or implemented by different development groups that maintain their own site maps and site map providers.

All SiteMapProvider objects are configured in the Web.config files. Any site map providers that are declared in these configuration files are loaded at run time and are used to load and process site navigation data. The SiteMap object, which keeps track of all the providers that are available to it through its Providers property collection, provides programmatic access to the navigation data that is managed by the providers. The following code example demonstrates the format that is used to declare a site map provider in a Web.config file.

<siteMap defaultProvider="<name>">
      name="<friendly name>"
      type="<fully qualified class name>, <assembly name (optional)>" 
      siteMapFile = "<file name>" />

The site navigation data that is loaded by these providers is used by other components of the site map infrastructure, such as the SiteMapPath and TreeView controls, to display site map information for users.

If you implement your own site map provider, you can place the source file in the App_Code directory of your ASP.NET application, and then the assembly will be compiled automatically. You can also place your own site map provider in the Global Assembly Cache (GAC), and provide a fully-qualified reference to it in the Web.config file. For more information on compiler services, see Working with Assemblies and the Global Assembly Cache.

Notes to Inheritors:

When you inherit from the SiteMapProvider class, you must override the following members: GetRootNodeCore, FindSiteMapNode, GetChildNodes, and GetParentNode.

The following code example demonstrates how to write a class that implements the abstract SiteMapProvider class. This example includes only a sample SiteMapProvider and a sample text file that works with it. To run the example you also need an entry in the Web.config file and an .aspx page. You can find these in the documentation for the SiteMapDataSource.SiteMapProvider property.

The example uses a comma-delimited file that follows an expected structure to load sitemap information. The first line of the file represents the root node of the sitemap, and subsequent lines are subnodes. Each subnode identifies its parent node by URL. An example of a file that meets these criteria is shown below.

default.aspx,Home,MyCompany Home Page,
sale.aspx,Now On Sale,Check Out These Great Deals!,default.aspx
catalog.aspx,Online Catalog,Browse Our Many Great Items!,default.aspx

The SimpleTextSiteMapProvider provides example implementations of all the SiteMapProvider properties and methods.

Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Configuration.Provider
Imports System.IO
Imports System.Security.Permissions
Imports System.Web

Namespace Samples.AspNet.VB

  <AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
  Public Class SimpleTextSiteMapProvider
    Inherits SiteMapProvider

    Private parentSiteMapProvider As SiteMapProvider = Nothing
    Private simpleTextProviderName As String = Nothing
    Private sourceFilename As String = Nothing
    Private aRootNode As SiteMapNode = Nothing
    Private siteMapNodes As ArrayList = Nothing
    Private childParentRelationship As ArrayList = Nothing

    ' A default constructor. The Name property is initialized in the
    ' Initialize method.
    Public Sub New()
    End Sub 'NewNew

    ' Implement the CurrentNode property.
    Public Overrides ReadOnly Property CurrentNode() As SiteMapNode
        Dim currentUrl As String = FindCurrentUrl()
        ' Find the SiteMapNode that represents the current page.
        Dim aCurrentNode As SiteMapNode = FindSiteMapNode(currentUrl)
        Return aCurrentNode
      End Get
    End Property

    ' Implement the RootNode property.
    Public Overrides ReadOnly Property RootNode() As SiteMapNode
        Return aRootNode
      End Get
    End Property

    ' Implement the ParentProvider property.
    Public Overrides Property ParentProvider() As SiteMapProvider
        Return parentSiteMapProvider
      End Get
      Set(ByVal value As SiteMapProvider)
        parentSiteMapProvider = Value
      End Set
    End Property

    ' Implement the RootProvider property.
    Public Overrides ReadOnly Property RootProvider() As SiteMapProvider
        ' If the current instance belongs to a provider hierarchy, it
        ' cannot be the RootProvider. Rely on the ParentProvider.
        If Not (Me.ParentProvider Is Nothing) Then
          Return ParentProvider.RootProvider
          ' If the current instance does not have a ParentProvider, it is
          ' not a child in a hierarchy, and can be the RootProvider.
          Return Me
        End If
      End Get
    End Property

    ' Implement the FindSiteMapNode method.
    Public Overrides Function FindSiteMapNode(ByVal rawUrl As String) As SiteMapNode
      ' Does the root node match the URL?
      If RootNode.Url = rawUrl Then
        Return RootNode
        Dim candidate As SiteMapNode = Nothing
        ' Retrieve the SiteMapNode that matches the URL.
        SyncLock Me
          candidate = GetNode(siteMapNodes, rawUrl)
        End SyncLock
        Return candidate
      End If
    End Function 'FindSiteMapNode

    ' Implement the GetChildNodes method.
    Public Overrides Function GetChildNodes(ByVal node As SiteMapNode) As SiteMapNodeCollection
      Dim children As New SiteMapNodeCollection()
      ' Iterate through the ArrayList and find all nodes that have the specified node as a parent.
      SyncLock Me
        Dim i As Integer
        For i = 0 To childParentRelationship.Count - 1

          Dim de As DictionaryEntry = CType(childParentRelationship(i), DictionaryEntry)
          Dim nodeUrl As String = CType(de.Key, String)

          Dim parent As SiteMapNode = GetNode(childParentRelationship, nodeUrl)

          If Not (parent Is Nothing) AndAlso node.Url = parent.Url Then
            ' The SiteMapNode with the Url that corresponds to nodeUrl
            ' is a child of the specified node. Get the SiteMapNode for
            ' the nodeUrl.
            Dim child As SiteMapNode = FindSiteMapNode(nodeUrl)
            If Not (child Is Nothing) Then
              children.Add(CType(child, SiteMapNode))
              Throw New Exception("ArrayLists not in sync.")
            End If
          End If
        Next i
      End SyncLock
      Return children
    End Function 'GetChildNodes

    Protected Overrides Function GetRootNodeCore() As SiteMapNode
      Return RootNode
    End Function ' GetRootNodeCore()

    ' Implement the GetParentNode method.
    Public Overrides Function GetParentNode(ByVal node As SiteMapNode) As SiteMapNode
      ' Check the childParentRelationship table and find the parent of the current node.
      ' If there is no parent, the current node is the RootNode.
      Dim parent As SiteMapNode = Nothing
      SyncLock Me
        ' Get the Value of the node in childParentRelationship
        parent = GetNode(childParentRelationship, node.Url)
      End SyncLock
      Return parent
    End Function 'GetParentNode

    ' Implement the ProviderBase.Initialize method.
    ' Initialize is used to initialize the state that the Provider holds, but
    ' not actually build the site map.
    Public Overrides Sub Initialize(ByVal name As String, ByVal attributes As NameValueCollection)
      SyncLock Me
        MyBase.Initialize(name, attributes)
        simpleTextProviderName = name
        sourceFilename = attributes("siteMapFile")
        siteMapNodes = New ArrayList()
        childParentRelationship = New ArrayList()
        ' Build the site map in memory.
      End SyncLock
    End Sub 'Initialize

    ' Private helper methods
    Private Function GetNode(ByVal list As ArrayList, ByVal url As String) As SiteMapNode
      Dim i As Integer
      For i = 0 To list.Count - 1
        Dim item As DictionaryEntry = CType(list(i), DictionaryEntry)
        If CStr(item.Key) = url Then
          Return CType(item.Value, SiteMapNode)
        End If
      Next i
      Return Nothing
    End Function 'GetNode

    ' Get the URL of the currently displayed page.
    Private Function FindCurrentUrl() As String
        ' The current HttpContext.
        Dim currentContext As HttpContext = HttpContext.Current
        If Not (currentContext Is Nothing) Then
          Return currentContext.Request.RawUrl
          Throw New Exception("HttpContext.Current is Invalid")
        End If
      Catch e As Exception
        Throw New NotSupportedException("This provider requires a valid context.", e)
      End Try
    End Function 'FindCurrentUrl

    Protected Overridable Sub LoadSiteMapFromStore()
      Dim pathToOpen As String
      SyncLock Me
        ' If a root node exists, LoadSiteMapFromStore has already
        ' been called, and the method can return.
        If Not (aRootNode Is Nothing) Then
          pathToOpen = HttpContext.Current.Server.MapPath("~" & "\\" & sourceFilename)
          If File.Exists(pathToOpen) Then
            ' Open the file to read from.
            Dim sr As StreamReader = File.OpenText(pathToOpen)

              ' Clear the state of the collections and aRootNode
              aRootNode = Nothing

              ' Parse the file and build the site map
              Dim s As String = ""
              Dim nodeValues As String() = Nothing
              Dim temp As SiteMapNode = Nothing

                s = sr.ReadLine()

                If Not s Is Nothing Then
                  ' Build the various SiteMapNode objects and add
                  ' them to the ArrayList collections. The format used
                  nodeValues = s.Split(","c)

                  temp = New SiteMapNode(Me, _
                      HttpRuntime.AppDomainAppVirtualPath & "/" & nodeValues(0), _
                      HttpRuntime.AppDomainAppVirtualPath & "/" & nodeValues(0), _
                      nodeValues(1), _

                  ' Is this a root node yet?
                  If aRootNode Is Nothing AndAlso _
                    (nodeValues(3) Is Nothing OrElse _
                     nodeValues(3) = String.Empty) Then
                    aRootNode = temp

                    ' If not the root node, add the node to the various collections.

                    siteMapNodes.Add(New DictionaryEntry(temp.Url, temp))

                    ' The parent node has already been added to the collection.
                    Dim parentNode As SiteMapNode = _
                        FindSiteMapNode(HttpRuntime.AppDomainAppVirtualPath & "/" & nodeValues(3))

                    If Not (parentNode Is Nothing) Then
                      childParentRelationship.Add(New DictionaryEntry(temp.Url, parentNode))
                      Throw New Exception("Parent node not found for current node.")
                    End If
                  End If
                End If
              Loop Until s Is Nothing
            End Try
            Throw New Exception("File not found")
          End If
        End If
      End SyncLock
    End Sub 'LoadSiteMapFromStore
  End Class 'SimpleTextSiteMapProvider
End Namespace

.NET Framework
Available since 2.0

Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top