asp.net-mvc - ASP.NET-MVC。如何从URL获取 Controller 名称?

标签 asp.net-mvc asp.net-mvc-routing

如何使用我在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/

相关文章:

asp.net-mvc - 在每个 Visual Studio 应用程序发布上重置 IIS 应用程序池标识权限

asp.net-mvc - 没有任何 ORM 的 ASP.NET MVC 4 项目

asp.net-mvc-2 - MVC 参数中的加号 (+) 在 IIS 7.0 上导致 404

c# - 如何格式化 DateTime 以在 Razor 生成的 View 中仅显示为一天中的时间?

asp.net-mvc - 如何在 App_Code 文件夹中的 Razor View 中使用 Url.Action

asp.net-mvc - MVC 3 远程验证字段具有复杂的名称

asp.net-mvc - Url.RouteUrl 返回 null

javascript - MVC3 自定义路由存在虚拟目录问题

c# - 路由前缀 VS Controller 名称(Web api)

c# - 如何忽略 ASP.NET MVC 路由中的特定路由