21
NovWhat is Routing in .NET Core?
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?
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.
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:
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
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.
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.
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:
- :int
- :bool
- :datetime
- :decimal
- :guid
- :length(min,max)
- :alpha
- :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?
Result | Behavior |
ContentResult | Returns a string |
FileContentResult | Returns file content |
FilePathResult | Returns file content |
FileStreamResult | Returns file content. |
EmptyResult | Returns nothing |
JavaScriptResult | Returns script for execution |
JsonResult | Returns JSON formatted data |
Views in ASP.NET Core
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
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.