Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Removing controller name from URL

Tags:

asp.net-mvc

I want to remove the controller name from my URL (for one specific controller). For example:

http://mydomain.com/MyController/MyAction

I would want this URL to be changed to:

http://mydomain.com/MyAction

How would I go about doing this in MVC? I am using MVC2 if that helps me in anyway.

like image 821
James Avatar asked Jul 26 '10 17:07

James


People also ask

How do you give a controller a URL?

If you just want to get the path to a certain action, use UrlHelper : UrlHelper u = new UrlHelper(this. ControllerContext. RequestContext); string url = u.

What is the controller in the URL pattern?

Typical URL Patterns in MVC Applications The MvcHandler HTTP handler determines which controller to invoke by adding the suffix "Controller" to the controller value in the URL to determine the type name of the controller which will handle the request. The Action value in the URL determines, which Action method to call.


2 Answers

You should map new route in the global.asax (add it before the default one), for example:

routes.MapRoute("SpecificRoute", "{action}/{id}", new {controller = "MyController", action = "Index", id = UrlParameter.Optional});  // default route routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional} ); 
like image 93
rrejc Avatar answered Sep 26 '22 14:09

rrejc


To update this for 2016/17/18 - the best way to do this is to use Attribute Routing.

The problem with doing this in RouteConfig.cs is that the old route will also still work - so you'll have both

http://example.com/MyController/MyAction

AND

http://example.com/MyAction

Having multiple routes to the same page is bad for SEO - can cause path issues, and create zombie pages and errors throughout your app.

With attribute routing you avoid these problems and it's far easier to see what routes where. All you have to do is add this to RouteConfig.cs (probably at the top before other routes may match):

routes.MapMvcAttributeRoutes(); 

Then add the Route Attribute to each action with the route name, eg

[Route("MyAction")] public ActionResult MyAction() { ... } 
like image 31
niico Avatar answered Sep 26 '22 14:09

niico