다음을 통해 공유


ASP.NET MVC 5: Render Same Page With Multiple URLs Using Route Engine

Introduction

This article describes the simplest approach which allows one to render the same page from different URLs. An “area” is an ASP.NET alternative but has the downside that we would need to duplicate code. We would need the controller duplicated in each area.  Hence using the routing engine offers a more elegant solution.

Demo

Step 1

Create an MVC project.

http://www.c-sharpcorner.com/UploadFile/91c28d/render-same-page-with-multiple-urls-using-route-engine-in-as/Images/MVC%20project.jpg

http://www.c-sharpcorner.com/UploadFile/91c28d/render-same-page-with-multiple-urls-using-route-engine-in-as/Images/MVC.jpg

Step 2

Run the application, look at the URL.

http://www.c-sharpcorner.com/UploadFile/91c28d/render-same-page-with-multiple-urls-using-route-engine-in-as/Images/application.jpg

Step 3

Go to the route.config file and remove the default route and replace with the following code.

public class  RouteConfig // default route  
{  
    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}"); // new routing  
  
    routes.MapRoute("Default", "{type}/{controller}/{action}/{id}",  
        new { controller = "Home", action = "Index", id = UrlParameter.Optional },  
        new RouteValueDictionary  
        {  
            { "type",  "Customer|Admin" }    
        });  
}

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

Click the login button. See the URL. The URL still starts with customer / admin. This will continue throughout the life-cycle.

Conclusion

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

See Also

Asp.Net Portal