ASP.NET-MVC . How to get the controller name from an url?

asp.net-mvc, asp.net-mvc-routing

Solution

See Stephen Walther's blog post ASP.NET MVC Tip #13 – Unit Test Your Custom Routes

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.

This is my 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();
}

In my code above "MvcApplication" is the class name in the Global.asax.

Good luck !

Problem

How can I get the controller name of a relative Url, using the routes I have defined in Global.asax? Example: 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" } ``` from the string "~/en/products/list" I want to have products (the controller name). Is there any existing method that already does this?

Original source

Related problems