Web
Analytics
Routing in ASP.NET Core 2.2 | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Routing in ASP.NET Core 2.2

ASP.NET Core routing is a way by which we can create named routes to call controllers and their respective actions. When a user writes any URL, the controller is called as per routes defined by the developer. In ASP.NET routing may implement in two ways.

  1. Fluent Routing or Convention Routing
  2. Attribute Routing

Fluent Routing or Conventional Routing:

In this Routing, We write routes in configure method of Startup Class. All routes template and routes constraints are defined in Routes.MapRoute() Method.Here we can write custom routes. This approach is not appropriate for complex routes so In MVC5 attribute routing was introduced which also continue in asp.net core.

 Example of Conventional Routing in asp.net core 

app.UseMvc(routes =>
 {    
       routes.MapRoute(
                                    name:"default",
                                     template: "{controller=Home}/{action=Index}/{id?}“   ); 
});

Above method always defined in the configure method of startup class. Here name is for customer route key or name and template is defined for set route tokens or to add default controller and action. If we write various routes then route name key must be different otherwise compile-time error will be raised. {id?} shows that id is an optional parameter.

To see full code create two controller Home and Students by your own and write following code into startup class.

        app.UseMvc(routes =>
            {
                routes.MapRoute(
                   name: "student",
                   template: "student",
                   defaults: new { Controller = "Home", Action = "Index" });
                routes.MapRoute(
           name: "default1",
           template: "",
            defaults: new { Controller = "Student", Action = "Index" });

                routes.MapRoute(
                name: "default",
                template: "{Controller=Home}/{Action=Index}/{id?}"
                    );
// This Route may be called using https://localhost:44347/studentdata
                // https://localhost:44347/studentdata/
                // https://localhost:44347/studentdata/Student/Index
                // https://localhost:44347/studentdata/Student/Index/12?name=yogesh
                // https://localhost:44347/studentdata/Student/Index/14?name=yogesh

                routes.MapRoute(
             name: "default1",
                     template: "studentdata/{controller=Student}/{action=Index}/{id?}/{*querystring}"
                     );
             
            });
  • {controller=Home}/{action=Index}/{id?}
  • This template is made by sections separated by slashes and controller=Home and action=index are called named tokens.
  • Home and index are default values for named token i.e controller and action.
  • Any token end with? Is optional.
  • The token which ends with * is completely optional and always put in the end of route template. For Example{controller=Admin}/{action=Process}/{?id}?{*querystring}




route constraints in asp.net core

List of route constraints in asp.net core 2.2 :-

route constraints in asp.net core 2

Following are two ways to write routing constraints

routes.MapRoute(
                    name: "default3",
                    template: "MyHome/{controller=Student}/{action=Index}/{id:int?}"
                   
                    );
routes.MapRoute(
                    name: "default",
                    template: "MyHome/{controller}/{action}/{id?}",
                    defaults: new { controller = "Student", action = "Index" },
                    constraints: new { id = new IntRouteConstraint() }
                    );

Custom Route Handler in asp.net Core 2.2

Write the following method into startup.cs

private static RequestDelegate CustomRouteHandler()
        {
            return async (c) =>
            {
                await Task.Run(() => c.Response.Redirect("https://yogeshdotnet.com"));
            };
        }

Call it using the following code

  routes.MapRoute("yogesh", CustomRouteHandler());

After applying following code then if we write yogesh after domain name then website page will redirect to www.yogeshdotnet.com

ASP.NET Core area routing

First Create Area(Admin) using VS and add the following code into Startup.cs

First Way to Implement Routing in Area:-

app.UseMvc(routes =>
            {
                routes.MapRoute(
                  name: "areas",
                  template: "{area:exists}/{controller=Login}/{action=Index}/{id?}"
                );
            });

Note : Add Controller Login and Index Action and add Following Code, [Area(“Admin”)] is compulsory to add on controller level to perform asp.net areas Routing i.e

[Area("Admin")] 
    public class LoginController : Controller
    {
        public IActionResult Index()
        {
            return Content("Area Admin Login Controller and Index Action");
        }
    }

Note: Area routing must be placed first with non-area routing, area: exists is compulsory to add area routing.

This route may be called using http://localhost:111/Admin

Second Way to Implement Area Routing:-

Add Following code into startup.cs.

  app.UseMvc(routes =>
            {
                routes.MapAreaRoute(
    name: "default",
    areaName: "Guest",
    template: "Guest/{controller}/{action}/{id?}",
    defaults: new { controller = "GuestLogin", action = "Index" });
            });

Create an Area “Guest”, Add “GuestLogin” Controller and “Index” Action and add the following code into newly created controller.

[Area("Guest")]
    public class GuestLoginController : Controller
    {
        public IActionResult Index()
        {
            return Content("Area Guest Login Controller and Index Action");
        }
    }

This route may be called using http://localhost:111/Guest

We will see ASP.NET Core attribute routing in an upcoming blog.