Search code examples
asp.netvirtualpathprovider

SiteMap.CurrentNode returns null when using query parameter


I have written a custom ASP.NET sitemap provider, it works well but if I add a query parameter to a virtual path SiteMap.CurrentNode returns null - it does not find the page. I've put breakpoints in all my code and never once does it enter my virtual path provider with a query parameter. What am I missing here?


Solution

  • I found an answer to my question and post it here for later use. Seems the sitemap provider always uses the path without the querystring parameters when lookup up matching paths. The trick is to not use Reqest.RawUrl in your overriden SiteMapProvider.CurrentNode() function but rather use Request.Path ; I've posted my solution below:

    public class CustomSiteMapProvider : SiteMapProvider {
    
        // Implement the CurrentNode property.
        public override SiteMapNode CurrentNode {
            get {
                var currentUrl = FindCurrentUrl();
    
                // Find the SiteMapNode that represents the current page.
                var currentNode = FindSiteMapNode(currentUrl);
                return currentNode;
            }
        }
    
        // Get the URL of the currently displayed page.
        string FindCurrentUrl() {
            try {
                // The current HttpContext.
                var currentContext = HttpContext.Current;
    
                if (currentContext != null) return currentContext.Request.Path;
    
                throw new Exception("HttpContext.Current is Invalid");
    
            } catch (Exception e) {
                throw new NotSupportedException("This provider requires a valid context.", e);
            }
        }
        ...