将多个路由分配给一个方法,如何确定调用哪个路由? [英] Multiple routes assigned to one method, how to determine which route was called?
问题描述
此刻,我正在研究一个小型ASP.NET MVC项目.该项目是在几个月前发布的.但是,出于可用性和SEO的原因,现在应该实施更改.我决定使用属性路由来创建干净的URL.
I am working on a small ASP.NET MVC project at the moment. The project was released a few month ago. But changes should be implemented for usability and SEO reasons now. I decided to use attribute routing to create clean URLs.
当前产品页面的调用者:
At the moment a product page is called by:
hostname.tld/Controller/GetArticle/1234
hostname.tld/Controller/GetArticle/1234
我这样定义了一条新路线:
I defined a new Route like this:
[Route("Shop/Article/{id:int}/{title?}", Name = "GetArticle", Order = 0)]
public ActionResult GetArticle(int id, string title = null) {
// Logic
}
一切正常,但是由于向后兼容和SEO原因,旧路由仍然可用.并使用HTTP状态代码301重定向到新的URL.
Everything works fine, but because of backwards compatibility and SEO reasons, the old route should be still available. And redirected with HTTP status code 301 to the new URL.
我听说可以为一个动作分配多个路由,如下所示:
I've heard that it is possible to assign multiple routes to one action, like this:
[Route("Shop/Article/{id:int}/{title?}", Name = "GetArticle", Order = 0)]
[Route("Controller/GetArticle/{id:int}", Name = "GetArticle_Old", Order = 1)]
public ActionResult GetArticle(int id, string title = null) {
// Logic
}
但是我不知道这是一个好的解决方案还是如何确定调用哪条路线?
But I have no idea if this is a good solution or how to determine which route was called?
推荐答案
您可以查看ControllerContext.RouteData
,以弄清楚在一项操作中使用多条路线时,他们使用了哪条路线.
You can look at ControllerContext.RouteData
to figure out which route they used when using multiple routes for one action.
public const string MultiARoute = "multiA/{routesuffix}";
public const string MultiBRoute = "multiB/subB/{routesuffix}";
[Route(MultiARoute)]
[Route(MultiBRoute)]
public ActionResult MultiRoute(string routeSuffix)
{
var route = this.ControllerContext.RouteData.Route as Route;
string whatAmI = string.Empty;
if (route.Url == MultiARoute)
{
whatAmI = "A";
}
else
{
whatAmI = "B";
}
return View();
}
这篇关于将多个路由分配给一个方法,如何确定调用哪个路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!