Search code examples
c#asp.net-mvcmaproute

c# MVC 5 RouteConfig redirection


Recently I had to update my mvc webapplication so that a basic entity of the system is displayed in the UI with a different literal.

Lets say

Previously I had: "Vessels"

Now I am asked to make it: "Ships"

The urls where mapped as by convention: mysite/{controller}/{action}/{id}

So I had urls like :

mysite/Vessels/Record/1023 

mysite/Vessels/CreateVessel 

I did all the renaming in the User Interface so that the titles and labels are changed from Vessel to Ship and now I a m asked to take care of the urls as well.

Now, I do not want to rename the Controller names or the ActionResult method names, because it is some heavy refactoring and because it is VERY likely, that the literals will soon be required to change again... ;-)

Is there any quick solution for me by editing just the RouteConfig, or something like that, that could do the work with a couple of lines coding?


Solution

  • Yeah, just register the route that will map your VesselsController actions:

    public class MvcApplication : System.Web.HttpApplication
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    "Vessels",                                              // Route name
                    "Ship/{action}Ship/{id}",                               // URL with parameters
                    new { controller = "Vessel", id = "" }                  // Parameter defaults
                );
    
                routes.MapRoute(
                    "Default",                                              // Route name
                    "{controller}/{action}/{id}",                           // URL with parameters
                    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
                );
    
            }
    
            protected void Application_Start()
            {
                RegisterRoutes(RouteTable.Routes);
            }
        }
    

    Also make sure to register your route before default one. Because, in other case, default route will be executed first and you will get an exception because no ShipController is defined in your application.