MVC Non-Controller Routing in URL

How to configure ASP.NET MVC 3 routing so that it does not display the controller in the url?

Here are my routes

routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( "HomeActions", "{action}", new { action= "AboutUs" } ); 

I need url:

 mysite.com/AboutUs 

But I

  mysite.com/Home/AboutUs 
+6
source share
2 answers

I would talk in great detail about the URL you want to pave. And put it above the default route.

  routes.MapRoute( "HomeActions", "AboutUs", new { controller = "Home", action= "AboutUs" } ); routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); 

Being less specific with a route like the one you suggested may have undesirable consequences. Especially if the default route is listed below.

 routes.MapRoute( "HomeActions", "{action}", new { controller = "Home", action= "AboutUs" } ); 

For example, if the above route is added after the default, then the URL http://www.example.com/AboutUs will most likely match the route {controller = "AboutUs", action = "Index", id = UrlParamter.Optional }. If you added a route above the default, then look for the URL http://www.example.com/Users , which you might want to be an index action in the Users controller will now look for the Users action on the Home controller.

So, I would advise to be specific about such routes.

+18
source

You need to add a route without the {controller} and specify the name of the controller in the default parameter.

+6
source

Source: https://habr.com/ru/post/888441/


All Articles