如何确定任意 URL 是否与定义的路由匹配
如何判断字符串是否与特定的命名路由匹配?
我有这样的路线:
routes.MapRoute(
"FindYourNewRental",
"find-your-new-rental/{market}/{community}.html",
new { controller = "FindYourNewRental", action = "Community" }
);
string url = "http://www.website.com/find-your-new-rental/northerncalifornia/sacramento.html"
如何以编程方式判断“url”字符串是否与该路线匹配?像这样的东西:
// matches url with the named route "FindYourNewRental"
if (IsRouteMatch(url, "FindYourNewRental"))
{
// do something
}
public bool IsRouteMatch(string url, string routeName)
{
// How do I code this function
}
How can I tell if a string matches a particular named route?
I have a route like this:
routes.MapRoute(
"FindYourNewRental",
"find-your-new-rental/{market}/{community}.html",
new { controller = "FindYourNewRental", action = "Community" }
);
string url = "http://www.website.com/find-your-new-rental/northerncalifornia/sacramento.html"
How can I programmatically tell if the 'url' string matches that route? Something like this:
// matches url with the named route "FindYourNewRental"
if (IsRouteMatch(url, "FindYourNewRental"))
{
// do something
}
public bool IsRouteMatch(string url, string routeName)
{
// How do I code this function
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我通过添加一个自定义 RouteInfo 类解决了这个问题,该类使用提供的 url 和应用程序路径创建一个新的 HttpContext,并使用它来获取基于新 HttpContext 对象的 RouteData 实例。然后我可以评估控制器和操作值以查看匹配的路由。我将其连接到 Uri 类上的扩展方法。这感觉有点黑客,我希望有一种更干净的方法来做到这一点,所以我将保留这个问题,以防其他人有更好的解决方案。
ROUTEINFO 类:
URI 扩展方法:
用法:
或
添加奖励: 因为RouteInfo 类返回 RouteData 的实例,我也可以访问路由参数。这导致了另一个 Uri 扩展方法的创建:
现在可以像这样使用它:
I solved this by adding a custom RouteInfo class which creates a new HttpContext with the supplied url and application path and uses that to obtain an instance of RouteData based on the new HttpContext object. I can then evaluate the Controller and Action values to see which route was matched. I have this wired up to an extension method on the Uri class. It feels a bit hackish and I was hoping there was a cleaner way to do this so I'll leave the question open in case someone else has a better solution.
ROUTEINFO CLASS:
URI EXTENSION METHOD:
USAGE:
OR
ADDED BONUS: Because the RouteInfo class gives me back an instance of RouteData, I can access the route parameters as well. This led to the creation of another Uri extension method:
Which can now be used like so: