Sunday, May 26, 2019

Defining multiple routes in Asp.Net Core MVC

In the previous post we saw about Routing in Asp.Net Core MVC Applications, also we saw different ways of defining simple routing. However for more complex application this simple routing might not be enough, we might have to define different routing paths for each module in the application like

/Accounts/. . .
/Contacts/. . .
/Reports/. . .

In this post we shall see on how to define multiple routing paths in Asp.Net Core MVC.

Remember we defined a simple routing which by default was pointing to Home/Index, let us extend this by adding 2 more paths to this routing pointing to the Employee & Users controller, the route definition will be as follows.
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "UserRoute",
            template: "UserDetails/{action}/{id:int?}",
            defaults: new { controller = "Users", action = "Index" }
            );
        routes.MapRoute(
            name: "EmployeeRoute",
            template: "EmployeeDetails/{action}/{id:int?}",
            defaults: new { controller = "Employee", action = "Index" }
            );
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id:int?}");
    });

With the above route definition, any URL with UserDetails will use the UserRoute definition and will point to action methods in the Users controller.

http://localhost/UserDetails/Index
http://localhost/UserDetails/Create

similarly any URL with EmployeeDetails will use the EmployeeRoute definition and will point to action methods in the Employee controller.

http://localhost/EmployeeDetails
http://localhost/EmployeeDetails/Create

Any URL which is not handled by these route definitions will be handled by the 3rd and default route handler.

http://localhost/Home/Index


Search Flipkart Products:
Flipkart.com

No comments: