ASP.NET Core Routing

08 Jan 2024
Beginner
59.1K Views
11 min read  

ASP.NET Core Routing: An Overview

Routing is a pattern-matching system that monitors the incoming request and figures out what to do with that request. Typically, it is a way to serve the user's request. Feeling lost in the world of random ASP.NET, wasting time without progress? It's time for a change! Join our ASP.NET Core Training Online, where we'll guide you on an exciting journey to master ASP.NET efficiently and on schedule.

ASP.NET Core Routing

When a user request URLs from the server then URLs are handled by the routing system. The Routing system tries to find out the matching route pattern of the required Url with already registered routes which are map to controller, actions, files, or other items. If there is a matching route entry, then it processes the request i.e. serves the resource, otherwise, it returns a 404 error.

ASP.NET Core Routing

Routing Basics

The following code shows a basic example of routing:


var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

Routing uses a pair of middleware, registered by UseRouting and UseEndpoints:

  • UseRouting adds route matching to the middleware pipeline. This middleware looks at the set of endpoints defined in the app, and selects the best match based on the request.
  • UseEndpoints adds endpoint execution to the middleware pipeline. It runs the delegate associated with the selected endpoint.

Endpoints

The MapGet method is used to define an endpoint. An endpoint is something that can be:

  • Selected, by matching the URL and HTTP method.
  • Executed, by running the delegate.

Endpoints that can be matched and executed by the app are configured in UseEndpoints. For example, MapGet, MapPost, and similar methods connect request delegates to the routing system. Additional methods can be used to connect ASP.NET Core framework features to the routing system:

  • MapRazorPages for Razor Pages
  • MapControllers for controllers
  • MapHub for SignalR
  • MapGrpcService for gRPC

Endpoint metadata

Endpoints can have extra data attached to them. This extra data is called endpoint metadata.

  • The metadata can be processed by routing-aware middleware.
  • The metadata can be of any .NET type.

Types of Routing

There are two main ways to define routes in ASP.NET Core:

Types of Routing

1. Convention-Based Routing

It creates routes based on a series of conventions that represents all the possible routes in your system. Convention-based is defined in the Startup.cs file.

Convention-Based Routing Configuration & Mapping

Conventions based Routing Configuration
Conventions based Routing Mapping

2. Attribute Routing

It creates routes based on attributes placed on the controller or action level. Attribute routing provides us more control over the URL generation patterns which helps us in SEO.

ASP.NET Core Attribute Routing

Attribute Routing Tokens

One of the cool things about ASP.NET Core routing is its flexibility as compared to ASP.NET MVC5 routing since it provides tokens for [area], [controller], and [action]. These tokens get replaced by their values in the route table.

ASP.NET Core Attribute Routing Token

Mixed Routing

You can use Convention-based Routing and Attribute routing together. Even you should use both together since it's not possible to define attribute route for each and every action or controller. In that case, Convention-based Routing will help you.

Route Constraints

Route Constraints are used to restrict the type of passed value to an action. For example, if you expect an argument id as an integer type, then you have to restrict it to an integer type by using datatype in the curly brackets as {id:int}.

Following are the main route constraints you can use:

  1. :int

  2. :bool

  3. :datetime

  4. :decimal

  5. :guid

  6. :length(min,max)

  7. :alpha

  8. :range(min,max)

Optional Parameters

You can define your route parameter as optional in routes by adding a question mark (?) to the parameter's constraint as given below:


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

Default Values

In addition to route constraints and optional parameters, you can also specify the default values for your route parameters which will be used if values are not provided.


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

Performance Guidance for Routing

When an app has performance problems, routing is often suspected as a problem. The reason routing is suspected is that frameworks like controllers and Razor Pages report the amount of time spent inside the framework in their logging messages. When there's a significant difference between the time reported by controllers and the total time of the request:

  • Developers eliminate their app code as the source of the problem.
  • It's common to assume routing is the cause.

Routing is performance-tested using thousands of endpoints. It's unlikely that a typical app will encounter a performance problem just by being too large. The most common root cause of slow routing performance is usually a badly behaving custom middleware.

The following code sample demonstrates a basic technique for narrowing down the source of delay:


var logger = app.Services.GetRequiredService<ILogger<Program>>();

app.Use(async (context, next) =>
{
    var stopwatch = Stopwatch.StartNew();
    await next(context);
    stopwatch.Stop();

    logger.LogInformation("Time 1: {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
});

app.UseRouting();

app.Use(async (context, next) =>
{
    var stopwatch = Stopwatch.StartNew();
    await next(context);
    stopwatch.Stop();

    logger.LogInformation("Time 2: {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
});

app.UseAuthorization();

app.Use(async (context, next) =>
{
    var stopwatch = Stopwatch.StartNew();
    await next(context);
    stopwatch.Stop();

    logger.LogInformation("Time 3: {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
});

app.MapGet("/", () => "Timing Test.");
Summary

This article is meant to get you started with the concept of Routing. It's meant to show the most common uses, not all of them. To get hands-on with routing in ASP.NET Core, consider enrolling in our ASP.NET Core Certification Program.

FAQs

Q1. What are the two types of Routing

Convention-Based Routing and Attribute Routing are the two types of Routing.

Q2. What's the role of Route Constraints?

Route Constraints are used to restrict the type of passed value to an action.

Q3. How can you define Optional Parameters?

You can define your route parameter as optional in routes by adding a question mark (?) to the parameter's constraint.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Learn to Crack Your Technical Interview

Accept cookies & close this