What is routing in C# ASP.NET Core?

Routing is used to map requests to route handlers.

Routes are configured when the application starts up, and can extract values from the URL that will be used for request processing.

Routing basics

Routing uses routes (implementations of IRouter)

  • map incoming requests to route handlers
  • generate URLs used in responses

Routing is connected to the middleware pipeline by the RouterMiddleware class. ASP.NET MVC adds routing to the middleware pipeline as part of its configuration

URL matching

Incoming requests enter the RouterMiddleware which calls the RouteAsync method on each route in sequence.

The IRouter instance chooses whether to handle the request by setting the RouteContext Handler to a non-null RequestDelegate.

If a handler is set a route, it will be invoked to process the request and no further routes will be processed.

If all routes are executed, and no handler is found for a request, the middleware calls next and the next middleware in the request pipeline is invoked.

URL generation

URL generation follows a similar iterative process, but starts with user or framework code calling into the GetVirtualPath method of the route collection.

Each route will then have its GetVirtualPath method called in sequence until until a non-null VirtualPathData is returned

Creating routes

Routing provides the Route class as the standard implementation of IRouter. Route uses the route template syntax to define patterns that will match against the URL path when RouteAsync is called.

Route will use the same route template to generate a URL when GetVirtualPath is called.


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

The framework provides a set of extension methods for creating routes such as −