Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 774
Gregoire Avatar asked Oct 20 '09 03:10

Gregoire


People also ask

How do I find my controller name?

Get controller name In preceding code, we use the ViewContext object to access the RouteData of the current request. After that, we use the Values property to access the current routing path values. By passing the controller key to the Values property we can get the current controller name.

How can I get controller in MVC?

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller - Empty, and then click Add.

How can we detect that a MVC controller is called by post or get?

You can check the Request. HttpMethod property. Save this answer.

What is the controller in URL pattern?

The URL pattern is considered only after the domain name part in the URL. For example, the URL pattern "{controller}/{action}/{id}" would look like localhost:1234/{controller}/{action}/{id}. Anything after "localhost:1234/" would be considered as a controller name.


2 Answers

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"];
like image 183
John Sheehan Avatar answered Nov 15 '22 08:11

John Sheehan


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 !

like image 24
Laurel.Wu Avatar answered Nov 15 '22 07:11

Laurel.Wu