Asp.Net Core Endpoint Routing Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of ASP.NET Core Endpoint Routing

ASP.NET Core Endpoint Routing: A Comprehensive Guide

Endpoint Routing in ASP.NET Core is a fundamental feature that determines how HTTP requests are matched to specific handlers, such as MVC actions or Razor Pages. Introduced with ASP.NET Core 2.2 and significantly enhanced in later releases, it provides a powerful and flexible way to manage routing in modern web applications.

Key Features of Endpoint Routing

  1. Endpoint Metadata:

    • Endpoints in ASP.NET Core are not just URL patterns; they carry metadata that allows for richer and more dynamic routing scenarios. This metadata can include data required for authorization, CORS policies, and other cross-cutting concerns.
  2. Routing Middleware:

    • Endpoint Routing is implemented through routing middleware (UseRouting()), which runs early in the request pipeline. It parses the URL, matches it to an endpoint, and saves the matched endpoint to the HttpContext. Middleware further down the pipeline can then access the matched endpoint for processing the request.
  3. Endpoint Selector:

    • The endpoint selector determines which endpoint should handle the given HTTP request based on the request details and endpoint metadata. It supports various conditions, including HTTP methods, headers, and more.
  4. Middleware Integration:

    • Once an endpoint is selected, control is passed to the endpoint’s middleware for execution. This allows for a modular and composable architecture where different concerns can be separated into distinct middleware components.

How It Works:

  1. Registration of Endpoints:

    • Endpoints are registered in the application during the Startup.Configure method. This is done through routing builders like MapControllers(), MapDefaultControllerRoute(), MapRazorPages(), etc., which add endpoints with the necessary metadata.
  2. Endpoint Matching:

    • When an HTTP request arrives, the routing middleware examines the request URL and matches it against the registered endpoints. It uses a combination of URL patterns and metadata to find the best match.
  3. Middleware Execution:

    • After an endpoint is matched, any middleware specified for that endpoint is executed. This can include authentication, authorization, and other processing steps before the endpoint handler (like an MVC action) runs.

Comparison with Traditional Routing

  • Flexibility:

    • Traditional routing is limited to URL patterns and is closely tied to the MVC framework. Endpoint routing, on the other hand, supports more flexible scenarios by allowing metadata and middleware integration directly into the endpoint structure.
  • Performance:

    • Endpoint routing is designed to be more efficient and performant, especially in high-load scenarios. It uses a more optimized data structure for endpoint matching and can handle more complex routing scenarios with less overhead.
  • Scalability:

    • With its metadata-driven approach, endpoint routing can scale better with the application’s complexity. It integrates seamlessly with other .NET Core features, making it a scalable solution for modern web applications.

Practical Examples

  1. Mapping MVC Controllers:

    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();  // Registers MVC controller endpoints
        });
    }
    
  2. Map Razor Pages:

    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();  // Registers Razor Pages endpoints
        });
    }
    
  3. Custom Middleware:

    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/hello", async context =>
            {
                await context.Response.WriteAsync("Hello, endpoint routing!");
            });
    
            endpoints.MapGet("/custom-route", async context =>
            {
                await context.Response.WriteAsync("This is a custom route!");
            });
        });
    }
    

Conclusion

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement ASP.NET Core Endpoint Routing

Step 1: Set Up Your ASP.NET Core Project

First, make sure that you have the latest version of the .NET SDK installed. You can download it from the .NET website.

Once .NET SDK is installed, open your command line interface (CLI) or terminal and create a new ASP.NET Core web application using the following command:

dotnet new web -n EndpointRoutingExample

This command creates a new web application named "EndpointRoutingExample". Navigate into the project directory:

cd EndpointRoutingExample

Step 2: Understand the Default Routing Setup in ASP.NET Core

In ASP.NET Core 3.0 and later, endpoint routing is used by default. The template project has a minimal setup in Program.cs that includes routing setup.

Here's what the default Program.cs looks like:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

Step 3: Modify the Program.cs to Add Custom Routes

Let's replace the default setup with custom endpoint routing in Program.cs:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

// Define custom routes here
app.MapGet("/hello", () => "Hello, world!");
app.MapGet("/greet/{name}", (string name) => $"Hello, {name}!");
app.MapGet("/square/{number}", (int number) => number * number);

app.MapControllers();

app.Run();

Step 4: Create a Controller for More Complex Endpoints

If you want to handle more complex logic, you can use controllers. Add a new controller named MathController:

dotnet new controller -n MathController

This will create MathController.cs file inside Controllers. Modify this file to add an endpoint to a controller:

using Microsoft.AspNetCore.Mvc;

namespace EndpointRoutingExample.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class MathController : ControllerBase
    {
        [HttpGet("add/{a}/{b}")]
        public IActionResult Add(int a, int b)
        {
            return Ok(new { Result = a + b });
        }

        [HttpGet("multiply/{a}/{b}")]
        public IActionResult Multiply(int a, int b)
        {
            return Ok(new { Result = a * b });
        }
    }
}

Step 5: Run Your Application

Now that we have defined some endpoints, we can run our application to see them in action. Back in your command line interface, run:

dotnet run

Navigate to https://localhost:5001/hello and you should see "Hello, world!".

Try out the other endpoints:

  • https://localhost:5001/greet/John should return "Hello, John!".
  • https://localhost:5001/square/5 should return 25.
  • https://localhost:5001/Math/add/3/4 should return {"Result":7}.
  • https://localhost:5001/Math/multiply/3/4 should return {"Result":12}.

Top 10 Interview Questions & Answers on ASP.NET Core Endpoint Routing

Top 10 Questions and Answers on ASP.NET Core Endpoint Routing

1. What is ASP.NET Core Endpoint Routing?

2. How does ASP.NET Core Endpoint Routing differ from the traditional routing system in ASP.NET Core MVC?

Answer: Traditional routing in ASP.NET Core MVC is based on attribute and convention-based routing, where routes are defined using attributes on controllers and actions or global routing tables. Endpoint routing, however, uses a more unified model where all endpoint information, whether from MVC, Razor Pages, gRPC, or other middleware, is stored in a single endpoint list. Endpoint routing supports middleware to examine and manipulate the endpoint selection process, providing more flexibility and power.

3. How do you register a simple MVC endpoint in ASP.NET Core Endpoint Routing?

Answer: In ASP.NET Core, MVC routes are typically registered using the UseEndpoints middleware in the Startup.cs file's Configure method. Here’s an example:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Other middleware registrations...

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers(); // Registers MVC controllers as endpoints
    });
}

Alternatively, you can define routes explicitly using:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

4. Can you explain how Razor Pages use Endpoint Routing?

Answer: Razor Pages use endpoint routing by calling endpoints.MapRazorPages() within the UseEndpoints configuration. This method registers all Razor Pages in the application as endpoints. Here’s a typical setup:

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages(); // Registers Razor Pages as endpoints
});

When a Razor Pages route is matched, the framework directly invokes the corresponding Razor Page handler method.

5. How does Endpoint Routing work with gRPC services in ASP.NET Core?

Answer: gRPC services are registered using the MapGrpcService<TService>() method within the UseEndpoints configuration. This method sets up the necessary routing and middleware to handle gRPC calls. Here’s an example:

app.UseEndpoints(endpoints =>
{
    endpoints.MapGrpcService<GreeterService>(); // Registers a gRPC service
});

Each gRPC method corresponds to a unique endpoint in the endpoint list.

6. What is the purpose of the MapFallback method in Endpoint Routing?

Answer: The MapFallback method is used to define a fallback endpoint that handles requests that do not match any other specific endpoint. It’s commonly used to serve a static page or redirect to an error handler when no other route matches. Here’s an example:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapFallbackToFile("index.html"); // Serves index.html for unmatched routes
});

7. How can you register custom middleware to participate in endpoint routing?

Answer: Custom middleware can participate in the endpoint selection process by running before or after the UseRouting middleware. Middleware can add endpoint constraints or modify the endpoint list. Here’s an example of adding a custom middleware:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();

    app.UseMiddleware<MyCustomEndpointMiddleware>();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

MyCustomEndpointMiddleware can inspect or modify the endpoint collection before endpoint selection occurs.

8. How does Endpoint Routing handle optional route parameters?

Answer: Endpoint Routing supports optional route parameters by defining them with a question mark (?) in the route template. Here’s an example:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

In this route template, {id?} is an optional parameter. The route will match requests with and without the {id} segment.

9. How do you create a custom endpoint constraint in ASP.NET Core Endpoint Routing?

Answer: Custom endpoint constraints allow you to add validation logic to route parameters. To create a custom constraint, you implement the IHttpRouteConstraint interface. Here’s a simple example:

public class CustomConstraint : IRouteConstraint
{
    public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (values.TryGetValue(routeKey, out var value) && value is string strValue)
        {
            // Validation logic here
            return strValue.Length > 5;
        }
        return false;
    }
}

You then use this constraint in your route:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id:customConstraint}");
});

10. What are the benefits of using Endpoint Routing in ASP.NET Core applications?

Answer: Endpoint Routing offers several benefits, including:

  • Unified model: All types of endpoints, such as MVC, Razor Pages, gRPC, and middleware, are managed in a single endpoint list.
  • Middleware integration: Allows middleware to examine and modify routing decisions.
  • Improved performance: Endpoint routing is optimized for better performance and scalability.
  • Flexible routing: Supports advanced routing scenarios with optional parameters, constraints, and custom middleware.
  • Better error handling: Provides a clear and structured way to define fallback endpoints and error handling logic.

You May Like This Related .NET Topic

Login to post a comment.