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?
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.
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.
You can check the Request. HttpMethod property. Save this answer.
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.
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"];
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 !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With