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

3

6

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?

Whether answered 20/10, 2009 at 3:22 Comment(3)
Where is that going to be located at?Bohemianism
In an helper class that will extends UrlHelperWhether
#8830552Unadvised
S
4

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 !

Skunk answered 27/10, 2009 at 18:2 Comment(2)
Stephen Walther's blog link above, still works. However, once on his site, the download link fails and the link to Tip #12 also fails - so I cannot get a listing of the FakeHttpContext class. Do you know of other places to get similar functionality?Septuplicate
Tip #12 is here: stephenwalther.com/archive/2008/07/01/…Torse
G
8

You should probably add another route like George suggests but if you really just need the controller value derived from the route you can do this in your controller action methods:

var controller = (string)RouteData.Values["controller"];
Geniality answered 20/10, 2009 at 3:52 Comment(3)
How could I get the contrller name from an arbitrary url, not from RouteData?Whether
@Gregoire? Do you mean an arbitrary URL on your site or someone else's? If on your site, then he told you how.Worriment
No because it will work only for the current URL, if I don't do a mistake (it works with Http current context)Whether
S
4

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 !

Skunk answered 27/10, 2009 at 18:2 Comment(2)
Stephen Walther's blog link above, still works. However, once on his site, the download link fails and the link to Tip #12 also fails - so I cannot get a listing of the FakeHttpContext class. Do you know of other places to get similar functionality?Septuplicate
Tip #12 is here: stephenwalther.com/archive/2008/07/01/…Torse
W
1

I'm not sure what you're asking, so if my answer's wrong, it's because I'm guessing at what you want.

You can always add another route to your Global.asax. That's often the easiest way to deal with cases 'outside of the norm'.

If you want to return a list of products, you'll use this route:

routes.MapRoute(
            "ProductList",         
            "{language}/{products}/{action}/",
            new { controller = "Products", action = "List", language = "en" });

You can also replace products with the more generic {controller} if more than one type of entity is going to use this route. You should modify it for your needs.

For example, to make this a generic route that you can use to get a list of any product:

routes.MapRoute(
            "ProductList",         
            "{language}/{controller}/{action}/",
            new { controller = "Products", action = "List", language = "en" });

What this does is that it creates a route (that you should always place before your Default route) that says, "For whatever the user enters, give me the controller and action they ask for". (Such as /en/Products/List, or /en/Users/List).

To visit that controller, you simply need to navigate to the following: yoursite.com/en/products/list. You can also use the HTMLActionLink to visit the controller.

<%=Html.ActionLink("Product", "List", new { controller = Products }, null ) %>

I'm writing this without my IDE open, so the ActionLink may have an error in it.

Worriment answered 20/10, 2009 at 3:37 Comment(3)
Thanks for having taking the time to answer me, but what I am looking for is a "reverse" GetRoute function, ie from an url (not the current one), I want to be able to extract the controller nameWhether
@Whether Great, uh, why didn't you say that in the first place?Worriment
Sorry but I have done a mistake because I believed it was clear enoughWhether

© 2022 - 2024 — McMap. All rights reserved.