如何使用我在Global.asax中定义的路由获取相对URL的 Controller 名称?
例子:
如果我有这样的路线反抗:
routes.MapRoute(
"Default", // Route name
"{language}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "", language = "en" }
从字符串“〜/en/products/list”中,我想要产品( Controller 名称)。是否有任何现有的方法已经做到这一点?
最佳答案
参见Stephen Walther的博客文章ASP.NET MVC Tip #13 – Unit Test Your Custom Routes
项目MvcFakes具有旧的System.Web.Abstractions引用。所以你必须更换它
与新的并重新编译该项目以获取MvcFakes.dll。
这是我的代码:
public string getControllerNameFromUrl()
{
RouteCollection rc = new RouteCollection();
MvcApplication.RegisterRoutes(rc);
System.Web.Routing.RouteData rd = new RouteData();
var context = new FakeHttpContext("\\" + HttpContext.Request.Url.AbsolutePath);
rd = rc.GetRouteData(context);
return rd.Values["action"].ToString();
}
在我上面的代码中,“MvcApplication”是Global.asax中的类名称。
祝你好运 !
关于asp.net-mvc - ASP.NET-MVC。如何从URL获取 Controller 名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1592278/