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.
Step 2
Run the application, look at the URL.
*
Step 3
Go to the route.config file and remove the default route and add the following code to it.
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
- }
- }
-
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute("Default", "{type}/{controller}/{action}/{id}",
- new { controller = "Home", action = "Index", id = UrlParameter.Optional },
- new RouteValueDictionary
- {
- { "type", "Customer|Admin" }
- });
- }
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.