實現此目的的一種方法是通過繼承IRouteConstraint創建自定義RouteConstraint並將您的url保存在xml中。你需要知道的頁面模板類型,所以你可以在這樣一個枚舉存儲這樣的信息:
public enum TemplateType
{
Home,
Product,
Category
}
下面是一個示例XML,你可以用它來存儲數據:
<Sitemap>
<Item url="/home" TemplateType="Home" />
<Item url="/products/category" TemplateType="Category">
<Item url="/products/category/product" TemplateType="Product" />
</Item>
</Sitemap>
後您將需要方法來提取Sitemap節點並獲取特定節點。您只需要反序列化xml並遍歷它即可找到特定的url。
您的自定義RouteConstraing應該是這樣的:
public class CustomRouteConstraint : IRouteConstraint
{
#region IRouteConstraint Members
private TemplateType m_type;
public CustomRouteConstraint(TemplateType type)
:base()
{
m_type = type;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
bool returnValue = false;
SitemapNode sitemapNode = GetSiteMapNode(httpContext.Request);
if (sitemapNode != null && sitemapNode.TemplateType == m_type)
{
return true;
}
return returnValue;
}
#endregion
private static SitemapNode GetSiteMapNode(HttpRequestBase request)
{
//get the aboslute url
string url = request.Url.AbsolutePath;
return SitemapManager.GetSiteMapNode(url);
}
}
後你在的RegisterRoutes方法的Global.asax文件都的這地方,你需要做這樣的事情:
routes.MapRoute(
"", // Route name
route, // URL with parameters
new { lang = "en", region = "us", controller = "Category", action = "Index" },
new { param1 = new CustomRouteConstraint(TemplateType.Category) });
希望這會有所幫助。