Demystified: Routing in ASP.NET Core

Learn how routing in ASP.NET Core works to map incoming requests to respective controller actions

Routing maps incoming requests to the respective route handlers and generates outgoing URLs. ASP.NET Core is an open source, cross-platform, lean, and modular framework for building high-performance web applications.

Routing in ASP.NET Core is managed by the routing middleware in the Microsoft.AspNetCore.Routing namespace. The middleware handles requests and responses and inspects, routes, and even modifies the request and response messages that flow through the pipeline.

In essence, routing in ASP.NET Core maps the incoming URLs to the respective controller actions and then generates the corresponding outgoing URLs.

Here's how routing in ASP.NET Core works:

  1. When a new request arrives, the routing middleware parses the incoming URL.
  2. A matching route is searched in the RouteCollection.
  3. If a matching route is found, control is passed to the RouteHandler.
  4. If a matching route is not found, the next middleware is invoked.

A RouteCollection is defined in the Microsoft.AspNetcore.Routing namespace and comprises of a collection of Routes. The RouteHandler is a class that implements the IRouteHandler interface is responsible for handling the incoming request.

Configuring routes in ASP.NET Core

Routing in ASP.NET Core can be set up in two ways:

  • via attribute-based routing, where you must specify routing information as attributes on the controller actions.
  • via convention-based routing, where you create routes based on conventions and configure them using the Configure method of the Startup class.

Once you have Visual Studio 2017 and .NET Core installed in your system, follow these steps to create a new ASP.NET Core project in Visual Studio:

  1. Open the Visual Studio 2017 IDE.
  2. Choose File > New > Project.
  3. In the New Project window, select the ASP.NET Core Web Application project template.
  4. Specify the name and location for your project and click OK to save.
  5. In the next screen, select Web API from the list of templates displayed, deselect authentication and Docker support (you don’t need any of these for now), and save the project.

To work with the routing middleware, you should install the Microsoft.AspNetCore.Routing NuGet package via the NuGet Package Manager. To register routes, you should use the MapRoute method of the routing middleware.

How to configure convention-based routing

This code snippet illustrates how you can configure route by convention in the Startup class for the Startup.cs file:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }
     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseMvc(routes =>
      {
           routes.MapRoute(
            template: "{controller}/{action}");
     });
    }
}

This route can map URLs like the following:

http://somewebsite.com/home/index
http://somewebsite.com/authors/blogs

Now assume that you want to provide support for more specific routes like the following:

http://somewebsite.com/home/index/1
http://somewebsite.com/authors/blogs/10

Here’s the code for such routes:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseMvc(routes =>
    {
           routes.MapRoute(
           template: "{controller}/{action}/{id}");
    });
    }

Now suppose you want id to be only an integer. Specify such route constraints this way:

app.UseMvc(routes =>
    {
        routes.MapRoute(
            template: "{controller}/{action}/{id:int}");
    });

You can also specify a name for any given route; such routes are known as named routes. Named routes help you to have multiple routes with identical parameters. Here’s how:

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

How to configure attribute-based routing

Contrary to convention-based routing, you can use attribute-based routing with attributes on the action methods. Here’s how you can configure routes using attributes on your controller’s action methods:

public class AuthorsController : Controller
{
    [Route("Index")]
    public IActionResult Index()
    {
        return View();
    }
}

You can also specify multiple routes on your action method. Here's an example:

public class AuthorsController : Controller
{
    [HttpGet("")]
    [HttpGet("index")]
    public IActionResult Index()
    {
        return View();
    }
}

Copyright © 2018 IDG Communications, Inc.