路由基于相同的参数(s)模式和不同的网页形式
本文关键字:网页 模式 于相同 参数 路由 | 更新日期: 2023-09-27 18:15:25
我在web表单中实现路由:
这些是我的自定义路由
public static void MyCustomRoutes(RouteCollection routes)
{
routes.Ignore("{resource}.axd/{*pathInfo}");
routes.MapPageRoute("NewsByTitle",
"{NewsTitle}",
"~/News.aspx");
routes.MapPageRoute("BlogsByTitle",
"{BlogsTitle}",
"~/ViewBlogs.aspx");
}
在我的默认页面中,我有博客和新闻部分,当我点击News
时,它会导航到新闻页面,因为它首先在路由表中定义。
但是当我点击Blogs
时,它只采取新闻的路线。
这是Blogs
和News
的RedirectToRoute
新闻:
String Url = clsMethods.GetTileByStoryId(BlogId); //My Url Param
Response.RedirectToRoute("NewsByTitle", new { NewsTitle = Url });
String Url = clsMethods.GetTileByStoryId(BlogId);
Response.RedirectToRoute("BlogsByTitle", new { BlogsTitle = Url});
根据Mihir的建议,我已经创建了自定义约束,因此这将解决我在这里的需求,这就是我如何实现约束逻辑
public static void MyCustomRoutes(RouteCollection routes)
{
routes.Ignore("{resource}.axd/{*pathInfo}");
routes.MapPageRoute("NewsByTitle",
"{NewsTitle}",
"~/News.aspx",
false,
null,
new RouteValueDictionary
{ { "checkNewsRoute", new IsNewsConstraint() } });
routes.MapPageRoute("BlogsByTitle",
"{BlogsTitle}",
"~/ViewBlogs.aspx",
false,
null,
new RouteValueDictionary
{ { "checkRoute", new IsBlogConstraint()} });
}
这里是约束博客约束
public class IsBlogConstraint : IRouteConstraint
{
public bool Match
(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection
)
{
return clsMethods.checkRoute(Convert.ToString(values["BlogsTitle"]));
}
}
新闻约束
public class IsNewsConstraint : IRouteConstraint
{
public bool Match
(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection
)
{
return clsMethods.checkNewsRoute(Convert.ToString(values["NewsTitle"]));
}
}
我想你是在试图配置你的路由来映射以下URL模式。
- 新闻:http://www.website.com/title-of-the-news
- 博客:http://www.website.com/title-of-the-blog
根据您的配置,如果您尝试打开博客,它将带您到新闻页面,这是一个正确的行为,因为博客的URL与新闻路由匹配。
为了区分两个不同的页面,你需要为两种类型的新闻和博客配置一些特定的路径,就像我下面所做的那样。
routes.MapPageRoute("NewsByTitle", "news/{NewsTitle}", "~/News.aspx");
routes.MapPageRoute("BlogsByTitle", "blogs/{BlogsTitle}", "~/ViewBlogs.aspx");
- 新闻:http://www.website.com/news/title-of-the-news
- 博客:http://www.website.com/blogs/title-of-the-blog
如果你正在寻找你在问题中提到的解决方案,你需要实现路由约束,就像这里所做的那样。自定义约束帮助路由防止路由被匹配,除非某些自定义条件被匹配,在你的情况下是博客或新闻。
在该约束中,您可以编写一些逻辑来检查路径段是新闻还是博客并返回布尔值。因此,当news约束查找博客名称时,它不会将条目查找为news(在数据库中),并返回false,该路由将被忽略。