这应该工作得很好。确保您的 web.config 看起来像这样:
<siteMap defaultProvider="MvcSiteMapProvider" enabled="true">
<providers>
<clear />
<add name="MvcSiteMapProvider"
type="MvcSiteMapProvider.DefaultSiteMapProvider, MvcSiteMapProvider"
siteMapFile="~/Mvc.Sitemap" securityTrimmingEnabled="true" cacheDuration="5"
enableLocalization="true" scanAssembliesForSiteMapNodes="true" includeAssembliesForScan=""
excludeAssembliesForScan="" attributesToIgnore="visibility"
nodeKeyGenerator="MvcSiteMapProvider.DefaultNodeKeyGenerator, MvcSiteMapProvider" controllerTypeResolver="MvcSiteMapProvider.DefaultControllerTypeResolver, MvcSiteMapProvider" actionMethodParameterResolver="MvcSiteMapProvider.DefaultActionMethodParameterResolver, MvcSiteMapProvider" aclModule="MvcSiteMapProvider.DefaultAclModule, MvcSiteMapProvider" siteMapNodeUrlResolver="MvcSiteMapProvider.DefaultSiteMapNodeUrlResolver, MvcSiteMapProvider" siteMapNodeVisibilityProvider="MvcSiteMapProvider.DefaultSiteMapNodeVisibilityProvider, MvcSiteMapProvider" siteMapProviderEventHandler="MvcSiteMapProvider.DefaultSiteMapProviderEventHandler, MvcSiteMapProvider" />
</providers>
</siteMap>
重要的是 siteMapFile 设置正确。此外,请确保在您的 .sitemap 文件(在我的情况下为 Mvc.Sitemap)中设置正确:
<?xml version="1.0" encoding="utf-8" ?>
<mvcSiteMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0"
xsi:schemaLocation="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0 MvcSiteMapSchema.xsd"
enableLocalization="true">
<mvcSiteMapNode title="Home" controller="Home" action="Index">
<mvcSiteMapNode title="About" controller="Home" action="About"/>
<mvcSiteMapNode
title="Details"
action="Present"
dynamicNodeProvider="MvcApplication3.ItemDetailsDynamicNodeProvider, MvcApplication3" />
</mvcSiteMapNode>
</mvcSiteMap>
这里重要的一点是 dynamicNodeProvider 类型和程序集拼写正确并且定位正确。
这是完整性的 ItemDetailsDynamicNodeProvider
public class ItemDetailsDynamicNodeProvider : DynamicNodeProviderBase
{
public override IEnumerable<DynamicNode> GetDynamicNodeCollection()
{
var repository = new Repository();
foreach (var item in repository.GetItems())
{
var node = new DynamicNode(item.Slug, item.DisplayName);
node.RouteValues.Add("id", item.Slug);
System.Diagnostics.Debug.WriteLine(item.Slug);
yield return node;
}
}
}
public class Repository
{
public IEnumerable<Something> GetItems()
{
yield return new Something { Slug = "Slug1", DisplayName = "DisplayName1"};
yield return new Something { Slug = "Slug2", DisplayName = "DisplayName2" };
}
}
public class Something
{
public string Slug { get; set; }
public string DisplayName { get; set; }
}