实现此目的的一种方法是通过继承 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>
之后,您将需要提取站点地图节点并获取特定节点的方法。您只需要反序列化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);
}
}
在您的 Global.asax 文件中的 RegisterRoutes 方法中完成所有这些后,您需要执行以下操作:
routes.MapRoute(
"", // Route name
route, // URL with parameters
new { lang = "en", region = "us", controller = "Category", action = "Index" },
new { param1 = new CustomRouteConstraint(TemplateType.Category) });
希望这会有所帮助。