Home   |   QuickStart Welcome   |   ASP.NET   |   Web Services   |   How Do I...?   
  |   I want my samples in...      

ASP.NET 2.0 Quickstart Tutorials

Using the Site Navigation API

The Site Navigation API is a programming abstraction for navigation data that accesses navigation data using configurable providers. A site navigation provider separates the data storage details of navigation data from the rest of the API. The Site Navigation API exposes the navigation data through the SiteMap and SiteMapNode classes. The SiteMap class returns the SiteMapNode instance that corresponds to the current page. It also provides access to the provider(s) that have been configured for the Site Navigation feature. A SiteMapProvider has a rich API for performing the following tasks:
  • Retrieving SiteMapNode instances based on the current HttpContext, or based on an arbitrary URL.
  • Retrieving the parent, or child nodes of a SiteMapNode
  • Accessing the SiteMapNode for the current page, as well as the root SiteMapNode of the entire navigation hierarchy
  • Enforcing authorization rules so that only nodes visible to user are returned by the provider.
A SiteMapNode instance exposes basic navigation information and functionality including:
  • URL, title, and description properties are available as well as any custom attributes a developer added to a SiteMapNode
  • Obtain a node's parent as well as a node's children
  • Navigate through the sibling nodes before and after a node
  • Obtain a reference to the SiteMapProvider instance that returned a node
ASP.NET ships with a provider called the XmlSiteMapProvider. This provider consumes data from an XML file (web.sitemap) and returns SiteMapNode instances based on this data. The XmlSiteMapProvider also has the following functionality:
  • Multiple sitemap files can be linked together to form a single "virtual" set of navigation data
  • Multiple XmlSiteMapProvider instances can be linked together to form a single "virtual" set of navigation data
  • The provider can optionally filter returned nodes based on the file authorization and URL authorization rules currently in effect for a website.
When you have a reference to a SiteMapProvider, you can search the site navigation data for a specific node based on URL. This allows you to obtain references to SiteMapNode instances anywhere in your site navigation data. The combination of finding arbitrary SiteMapNode instances and the ability to navigate through site navigation data from any SiteMapNode allows you to easily walk through your site's navigation data.

As a developer, you can choose to store your navigational data in other data stores using other formats (for example - as relational data in a database). You can then author a custom provider that derives from SiteMapProvider.

Creating an Application Site Map

The navigation structures for the Site Navigation QuickStart samples are represented in Web.sitemap files. In the sitemap file that you can view below, the navigational structure for the entire QuickStart is shown. A Web.sitemap file contains a single top-level <siteMap> element. Nested within the <siteMap> element is at least one <siteMapNode> element. There must always be a top-level <siteMapNode> within a site map. The Site Navigation feature requires a single root <siteMapNode> to ensure that walking up a hierarchy of nodes is guaranteed to eventually converge on a single well-known node. You can nest as many <siteMapNode> elements beneath the root <siteMapNode> element as needed. Additionally, you can nest <siteMapNode> elements to any arbitrary depth.

An individual <siteMapNode> element usually contains a Url, Title and Description attribute. The Url attribute can indicate a virtual path that corresponds to a page in your application. It can also contain paths to pages in other applications, or URLs that point at completely different web sites. In the sample below, all of the Url attributes use application-relative syntax to reference paths located within the QuickStart application. The Title attribute is used as display text when rendering UI for navigational data. For example, the SiteMapPath control uses the Title attribute to render the text of the hyperlinks in the control. If a Description attribute is present, server controls may use this information to display tooltips or ALT text. A developer can also add custom attributes to a <siteMapNode> and these attributes will be available using the default indexer on the SiteMapNode class. For information on other attributes supported on the <siteMapNode> element please see the .NET Framework documentation.

Web.sitemap Example
Run Sample View Source

Programming with Site Navigation Classes

You can obtain site navigation data programmatically in code. The starting point for obtaining Site Navigation data programmatically is the SiteMap class. There are a variety of static methods on this class, the most important one being the CurrentNode property. On any page in your website, you can call SiteMap.CurrentNode to reference a piece of navigation data matching the currently executing page. Navigation data is returned as an instance of a SiteMapNode - when you call SiteMap.CurrentNode the property returns a SiteMapNode instance corresponding to the current page. The Site Navigation feature determines the correct node to return based upon navigation data that is stored in an XML file.

The following sample demonstrates a user control with simple paging. On the page that is displayed, the user control renders at the bottom center of the page. Initially there is link [Next Topic]. When you click on this link the user control calls the SiteMap object to determine whether or not there are sibling pages around the current page. From the SiteMap.CurrentNode property, the code determines if there are previous siblings (SiteMap.CurrentNode.PreviousSibling) as well as following siblings (SiteMap.CurrentNode.NextSibling). Based upon the existence of these siblings, the user control renders hyperlinks, setting each hyperlink's NavigateUrl property to the value of the sibling node's Url property.

If you click the various Treeview links on the left-hand side of the page, also notice how the user control automatically displays the appropriate [Next Topic] and [Previous Topic] links. The user control also renders a hyperlink that you can click on to return back to the home page. If you look at the code for how this hyperlink is rendered, the control uses a custom attribute on the home page <siteMapNode> element called "customAttribute". The control demonstrates how to use the SiteMapNode's default indexer to retrieve the value of this custom attribute.

VB SiteMap API
Run Sample View Source

Site Navigation Security

The Site Navigation feature can optionally filter the SiteMapNode instances returned by a provider based upon authorization rules. The XmlSiteMapProvider can filter nodes based on the file and URL authorization rules that apply to the current website.

The following sample uses forms authentication with predefined user credentials stored in web.config. In global.asax, roles are attached to the current request based on the username. In web.config, the <siteMap> element has its securityTrimmingEnabled attribute set to true. Also the web.config file defines a number of URL authorization rules at the bottom of the file. When you run the sample and log in, the XmlSiteMapProvider will automatically perform an authorization check for each SiteMapNode based on the combination of the roles the user belongs to and the authorization rules defined in web.config.

Try running the sample as one of the following three user accounts:
  • Userid: SectionOne    Password: SectionOne
  • Userid: SectionTwo    Password: SectionTwo
  • Userid: AllSections     Password: AllSections
There is a logout link in the upper right-hand corner of the page so that you can login and logout with different accounts. Notice how depending on which account you log in with, the navigation UI displayed in the Treeview and Menu controls automatically changes to reflect the URLs that each user is authorized to access. The provider automatically filters the returned nodes - no extra code is required for this behavior. Logging in as the user "SectionOne" results in only links for "SectionOne" and outside links being shown in the left-hand Treeview control. Logging in as the user "SectionTwo" results in only links for "SectionTwo" and outside links being shown in the left-hand Treeview control. Logging in as the user "AllSections" displays all links in the Treeview control. The authorization rules in web.config are configured to selectively grant access to the "SectionOne" and "SectionTwo" URL hierarchies.

This sample also demonstrates how security trimming works with URLs that lie outside of the directory scope for an application. In the web.sitemap file the roles attribute is used on the nodes for external links. The syntax roles="*" grants all users the right to retrieve and view that node in navigation controls. The syntax roles="Adminstrators,Regular Users" allows only users in those roles the right to retrieve and view the nodes in navigation controls. Since the global.asax file allocates the users in this sample to one of these two roles, you will always be able to view the external links.

Developers have the option to use both file/URL authorization rules and the roles attribute to control access to SiteMapNode instances. If both sets of information are available, a site navigation provider will attempt to authorize the current user based on both file/URL authorization rules as well as the roles in the roles attribute. If the current user passes either set of authorization checks, then the current user is granted access to the node.

If the default security trimming behavior is not suitable for your application, a developer can derive from XmlSiteMapProvider and override the IsAccessibleToUser method with a custom implementation for node authorization.

VB Site Navigation Security
Run Sample View Source

Localizing Site Map Data

Navigation data stored in a sitemap file may need to be localized. The URL, Title, and Description attributes on a <siteMapNode> element can all be localized. In addition, any custom attributes that a developer places on a <siteMapNode> element can also be localized.

The sample includes localized text for both the English and French languages. The web.sitemap file uses two types of localization expressions to accomplish this: implicit and explicit expressions. For more details on localization in general, as well as background information on the two types of localization expressions see the topic "Localizing Your Application" in the Quickstart. A sitemap file indicates that it uses localized data by the presence of enableLocalization=true on the root siteMap element.

In a sitemap file implicit expressions make it easy for a developer to tag each <siteMapNode> element with a lookup key that will be used to retrieve resources from a resource file. In the sample web.sitemap, implicit resource expressions are on every node except the first one. The syntax looks like: resourceKey="Autos". When the XmlSiteMapProvider retrieves a SiteMapNode based on information in the web.sitemap file, it will look for a string resource based on a combination of the name of the SiteMapNode property, the resourceKey and the value of the siteMapFile attribute configured for the provider. Using the "Autos" node as an example, the provider will look in a resource file that begins with "web.sitemap" based on the current culture. This means for a browser that sends a french language header, the provider will look for a resource file called web.sitemap.fr.resx. Within the resource file, the provider will look for a resource key whose name is based on resourceKey + "." + [name of the SiteMapNode property]. Using the Title property for the "Autos" node as an example, the provider will look a resource whose key is Autos.Title inside of the resource file called web.sitemap.fr.resx.

Explicit expressions give the developer more control over the files that contain localized resources as well as the name of resource key. In the sample web.sitemap, an explicit resource expression is used for the first <siteMapNode> element. Explicit expressions are specified on a per- attribute basis. The first <siteMapNode> element uses an explicit expression for the Title attribute. An explicit expression must always start with $resource: . After this identifier, a developer must provide the root name for the resource file, as well as the resource key. Optionally a developer can also supply a default value. In the sample, the expression $resources: Title, MyTitle , Home indicates that the provider should look in a resource file that starts with "Title". For a browser that sends a french language header, the provider would look for a resource file called Title.fr.resx. The provider would then look for a resource whose key is MyTitle. If the provider cannot find such a resource, it will fallback and use the string "Home" as the default value.

To see the effects of sitemap localization, run the sample. Browsers that indicate English as the default language will see English text returned. If using IE, you can change the default language by going to Tools-->Internet Options and selecting the "Languages" button on the "General" tab. Press the "Add" button and choose to add "French (France) [fr]" as a language. If necessary, select the option for the French language and press "Move Up" to make it the default language requested by IE. After changing the default language to French, refresh the sample page. Note that the text in the Menu, Treeview and SiteMapPath controls automatically change to reflect the French text stored in the French resource files located in the App_GlobalResources directory.

VB Sitemap Localization
Run Sample View Source

Modifying Site Navigation Data Returned by Providers

The navigation data contained in web.sitemap that is consumed by the XmlSiteMapProvider is static - the data is loaded into memory and stored as read-only data. However, many sites have a navigation structure that is parameterized based on querystring values. For example, a newsgroup site may have a well-defined structure of pages (e.g. a home page, a news category page, and a news article page), but the actual content will vary depending on identifiers in the querystring. Although it is possible to store every possible permutation of querystring values in <siteMapNode> elements, for even moderate numbers of querystring values a sitemap file could contain hundreds or thousands of <siteMapNode> elements.

The Site Navigation feature exposes the SiteMapResolve event on the SiteMapProvider base class. An event subscription can be made using either SiteMap.SiteMapResolve or directly against individual providers using SiteMap.Provider.SiteMapResolve. The return value from the event is a SiteMapNode instance. In your event handler you can write custom logic to create a hierarchy of SiteMapNode instances. This logic can modify the properties on each SiteMapNode so that properties like URL and Title reflect additional information based on data taken from the querystring.

The sample below registers an event handler in global.asax. The code for the event handler is in a class located in the App_Code directory. The custom class makes a clone of the SiteMapNode instance corresponding the current page. Since nodes from XmlSiteMapProvider are read-only, calling the Clone method on a SiteMapNode returns a writeable instance of the ndoe. In the sample the Clone method is passed a value of true, which results in a writeable copy of the current SiteMapNode as well as all of the node's parents. The remainder of the code in the class inspects the current page and the current page's querystring to determine where in the site hierarchy the current page is located. The code fixes up the URL and Title properties by including additional information so that navigation UI rendered by the SiteMapPath control reflects the actual click-path the website user followed to reach the current page.

When you run the sample you will initially be on the home page of the site. The SiteMapPath control will reflect this as well. Clicking on either of the links will bring you to a category page that displays links to news articles relevant to a specific news category. Notice that if you hover over the last link in the SiteMapPath control, the URL displayed in the browser's status bar includes the querystring information specifying the type of news category. Clicking on one of the posting links brings you to the news posting page. If you hover over the links in the SiteMapPath control, notice that the last two links in the control have URLs and Titles that contain the correct querystring and descriptive information based on the clickpath. If you navigate back to the home page of the site, try clicking the other set of newsgroup and content links, and again notice how the SiteMapPath control is updated to reflect the second set of links that you clicked.

VB Using the SiteMapResolve Event
Run Sample View Source