What is Routing in .NET Core?

What is Routing in .NET Core?

24 Jun 2024
Beginner
62.4K Views
14 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. Join our ASP.NET Core Training Online, where we'll guide you on an exciting journey to master ASP.NET efficiently and on schedule.

Read More: Top 50 ASP.NET Core Interview Questions and Answers for 2024

How Does Routing Work in ASP.NET Core?

How Does Routing Work in ASP.NET Core?

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.

How Does Routing Work in ASP.NET Core?

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 in Asp.net Core

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

Types of Routing in Asp.net Core

Read More: What is an ASP.NET Core Developer? Skills to become ASP.NET Core Developer

1. Convention-Based Routing

It creates routes based on a series of conventions representing 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 an attribute route for 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?}");
});

Read More: Salary Offered to ASP.NET Developers

What Are Action Results?

There are a lot of action results, some of which are listed below along with their behaviors.
ResultBehavior
ContentResult Returns a string
FileContentResult Returns file content
FilePathResult Returns file content
FileStreamResultReturns file content.
EmptyResultReturns nothing
JavaScriptResult Returns script for execution
JsonResultReturns JSON formatted data

Views in ASP.NET Core

In an ASP.NET Core MVC application, there is nothing called a webpage i.e. everything that you see is a view. In such applications, the response to a request is a view or the controller might redirect the request to another controller action. One of the most popular methods for creating HTML in the MVC Framework is to use the Razor View Engine in ASP.NET MVC.

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.");

Advantages of Conventional Routing

  • Centralized Configuration: It provides a centralized location to manage URL routing rules, making it easier to understand and manage the application’s URL structure.
  • URL Generation: It simplifies the generation of URLs, so that you can use routing names and parameters to generate URLs without hard-coding them.
  • Clear URL Structure: It encourages a clear and hierarchical URL structure, which can improve the discoverability of URLs and make them more intuitive.

Considerations for Conventional Routing

  • Complexity for Dynamic URLs: For applications that require dynamic URL patterns, conventional routing can become complex and hard to manage.
  • Routing Conflicts: Improper configuration can lead to routing conflicts where multiple routes match a URL, leading to unexpected behavior.
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.

Q4. What is the default route in .NET Core?

In ASP.NET Core, the default route is defined as "{controller=Home}/{action=Index}/{id?}".

Q5. What are route values in ASP.NET Core?

In ASP.NET Core, route values represent the parameters or data values extracted from the URL route pattern during routing.

Take our Aspnet skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details

Can't find convenient schedule? Let us know

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.
Accept cookies & close this