ASP.NET MVC的。如何从一个URL中的控制器名称? [英] ASP.NET-MVC . How to get the controller name from an url?
问题描述
如何能得到一个相对URL的控制器名称,用我在Global.asax中定义的路线?
How can I get the controller name of a relative Url, using the routes I have defined in Global.asax?
例如:
如果我有一个路线defiend是这样的:
if I have a route defiend like this:
routes.MapRoute(
"Default", // Route name
"{language}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "", language = "en" }
从字符串〜/ EN /产品/列表我想对我们的产品(控制器名称)。有没有已经这样做了任何现有的方法?
from the string "~/en/products/list" I want to have products (the controller name). Is there any existing method that already does this?
推荐答案
请参阅斯蒂芬·瓦尔特的博客文章<一个href=\"http://stephenwalther.com/blog/archive/2008/07/02/asp-net-mvc-tip-13-unit-test-your-custom-routes.aspx\"相对=nofollow> ASP.NET MVC提示#13 - 单元测试您的自定义路线
See Stephen Walther's blog post ASP.NET MVC Tip #13 – Unit Test Your Custom Routes
该项目MvcFakes有一个老System.Web.Abstractions参考。所以,你必须更换
用新和recomply项目以获得MvcFakes.dll
The project MvcFakes has an old System.Web.Abstractions reference. So you must replace it with the new one and recomply the project to get MvcFakes.dll.
这是我的code:
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();
}
在我的code以上MvcApplication是在Global.asax类名。
In my code above "MvcApplication" is the class name in the Global.asax.
祝你好运!
这篇关于ASP.NET MVC的。如何从一个URL中的控制器名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!