如何在运行时添加新的MvcSitemapProvider节点
本文关键字:MvcSitemapProvider 节点 添加 运行时 | 更新日期: 2023-09-27 17:57:49
我正在开发一个类似asp.net的mvc 4网站,该网站具有wcf服务数据层。我的应用程序是用主类别、子类别和产品构建的。每个产品只能在一个子类别中,我的url如下:
/主分类名称/子分类名称/{productiond}/producttitle
以及相应的面包屑轨迹:
首页>主分类>子分类>产品名称
我目前正在使用MvcSitemapProvider来生成导航菜单和面包屑。我正在加载所有的url作为动态节点没有缓存。这个解决方案适用于几个产品,但当我添加1000个产品时,网站地图需要6.5秒才能填充,这太长了。
我在MvcSitemapProvider中打开了缓存。这样应用程序的加载速度会更快。但当用户添加新产品并导航到此新产品(页面)时。该url尚未在网站地图文件中,因为它使用了缓存。这样我的导航和面包屑就不会生成。
我的问题是:
用户添加新产品后,是否可以在运行时向网站地图添加新节点
接受的答案现在有点过时了。在MvcSiteMapProvider v4中,DynamicNodeProvider中不再有GetCacheDescription()方法。这似乎无论如何都不起作用。
现在,您可以使用更新数据的操作方法上的[SiteMapCacheRelease]属性手动使缓存无效:
[MvcSiteMapProvider.Web.Mvc.Filters.SiteMapCacheRelease]
[HttpPost]
public ActionResult Edit(int id)
{
// Update the record
return View();
}
或者通过调用静态方法:
MvcSiteMapProvider.SiteMaps.ReleaseSiteMap();
现在您还可以选择扩展框架以提供自己的缓存依赖项。
MvcSiteMapProvider允许解决缓存依赖关系的动态站点映射。
您可以通过创建一个实现IDynamicNodeProvider
的类来启用此功能。下面是一个示例,它基于数据库查询生成动态节点,并在同一查询上设置缓存依赖项。
public class ProductNodesProvider : IDynamicNodeProvider
{
static readonly string AllProductsQuery =
"SELECT Id, Title, Category FROM dbo.Product;";
string connectionString =
ConfigurationManager.ConnectionStrings ["db"].ConnectionString;
/// Create DynamicNode's out of all Products in our database
public System.Collections.Generic.IEnumerable<DynamicNode> GetDynamicNodeCollection()
{
var returnValue = new List<DynamicNode> ();
using (SqlConnection connection = new SqlConnection(connectionString)) {
SqlCommand command = new SqlCommand (AllProductsQuery, connection);
connection.Open ();
SqlDataReader reader = command.ExecuteReader ();
try {
while (reader.Read()) {
DynamicNode node = new DynamicNode ();
node.Title = reader [1];
node.ParentKey = "Category_" + reader [2];
node.RouteValues.Add ("productid", reader [0]);
returnValue.Add (node);
}
} finally {
reader.Close ();
}
}
return returnValue;
}
/// Create CacheDependancy on SQL
public CacheDescription GetCacheDescription ()
{
using (SqlConnection connection = new SqlConnection(connectionString)) {
SqlCommand command = new SqlCommand (AllProductsQuery, connection);
SqlCacheDependency dependancy = new SqlCacheDependency (command);
return new CacheDescription ("ProductNodesProvider")
{
Dependencies = dependancy
};
}
}
}
虽然这一切都很漂亮,而且当您的客户更改数据库中的产品时,应该会使缓存无效,但整个SqlCacheDependancy
可能很棘手,并且依赖于SQL Server版本。
如果您使用缓存来存储产品,则可以使用自定义CacheDependacy
。