Render Same Page With Multiple URLs Using Route Engine in ASP.Net MVC 5

Introduction

Here I'm demonstrating a technique to render the same page with different URLS. We have an “area” in ASP.NET to do the same. But we can't use an area for this because we need to duplicate (create the same controller in both areas) the code. So we will do this by exploring route engine.

Step 1

Create a MVC project.

MVC project

MVC

Step 2

Run the application, look at the URL.

*pplication

Step 3

Go to the route.config file and remove the default route and add the following code to it.

  1. public class RouteConfig // default route  
  2. {  
  3.     public static void RegisterRoutes(RouteCollection routes)  
  4.     {  
  5.         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  6.   
  7.         routes.MapRoute(  
  8.             name: "Default",  
  9.             url: "{controller}/{action}/{id}",  
  10.             defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
  11.         );  
  12.     }  
  13. }  
  14.   
  15. public static void RegisterRoutes(RouteCollection routes)  
  16. {  
  17.     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // new routing  
  18.  
  19.     routes.MapRoute("Default""{type}/{controller}/{action}/{id}",  
  20.         new { controller = "Home", action = "Index", id = UrlParameter.Optional },  
  21.         new RouteValueDictionary  
  22.         {  
  23.             { "type""Customer|Admin" }   
  24.         });  

Now we have created two “types” in the routing using RouteValueDictionary.

Step 4

Again run the application, you will get the following error screen.



Why? Do you have any idea about the new URL? Yes. It starts with Customer or Admin.

Step 5

Here is the admin home page. See the URL.



Here is the customer home page. See the URL.



Step 6

I clicked on the login button. See the URL. The URL still starts with customer / admin. This will continue throughout the lifecycle.



Conclusion

This is the simplest and trickiest method to change the URLs.


Similar Articles