Introduction to Routing in .NET Core Web Applications
.NET Core Web Applications and Routing Basics

Introduction to Routing in .NET Core Web Applications

There are various types of ASP .NET Core web applications, including MVC application, Razor Pages application, Signal R application, Web API application, and even gRPC service application. These web applications have one common thing, they can be accessed using URLs and for every URL some code is executed by the web server.

In this article, let’s understand basics of how routing works in any ASP .NET Core web applications.

URL and Endpoints

We already know that a web application can be accessed using URLs. In .NET, the request processing pipeline has two important responsibilities:

  • Identify the endpoint that can handle the request
  • Dispatch all inputs to the selected endpoint to process the request.

Concepts

Routing is the process of matching incoming HTTP URL and then dispatching all information to appropriate endpoint, which executes the intended code.

An endpoint is a basic unit of executable code. An endpoint has two important characteristics:

  • It should be able to select an endpoint using incoming URL and HTTP action.
  • It should be able to execute an endpoint by running an delegate

Code

This explanation might appear too abstract. But to understand, let’s try to have look at some code. Let’s see the methods provided by EndpointRouteBuilderExtensions class. Some of the methods are:

  • MapGet – Adds a RouteEndpoint that matches HTTP GET requests for the specified pattern
  • MapPost – Adds a RouteEndpoint that matches HTTP POST requests for the specified pattern
  • MapPut – Adds a RouteEndpoint that matches HTTP PUT requests for the specified pattern
  • MapDelete – Adds a RouteEndpoint that matches HTTP DELETE requests for the specified pattern.

There are some other methods, which are specific to the type of .NET core web application, e.g.

Routing Middlewares

There are two different middlewares that are used for enabling routing in ASP .NET Core web application.

  • UseRouting – to select appropriate endpoint based on URL and HTTP action. This code goes through all the endpoints defined in an application and selects the best possible match. This selected endpoint can then be used by subsequent routing aware middleware.
  • UseEndpoints – Adds the endpoint execution to the request pipeline. It is also responsible to run the delegate associated with selected endpoint.

Below is code sample showing how a simplistic .NET Core web application can be configured. It has only two endpoints:

  • An endpoint “/” returns Hello World string in the response.
  • The other endpoint “/” and some other token {name}, which prints a string Hello followed by value of incoming token.

Both endpoints allow HTTP GET requests.

Note that this application is just for demo, to explain the concepts of routing.

// Program.cs showing Main method
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
// Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
// app.Cors();
// app.UseAuthentication()
// app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
// Default Endpoint
endpoints.MapGet("/", async (context) =>
{
await context.Response.WriteAsync($"Hello World");
});
// Name Token Endpoint
endpoints.MapGet("/{name}", async (context) =>
{
// Read input token and add it to response
var name = context.Request.RouteValues["name"];
await context.Response.WriteAsync($"Hello {name}");
});
});
}
}
view raw Startup.cs hosted with ❤ by GitHub

Point to Note

Once an endpoint is selected, the routing aware middleware can use that data to decide additional functionality required for the endpoint.

Some examples include applying CORS policies, Authentication and Authorization middleware etc. An application might have different authorizations and authentication needs for endpoints.

So, the middleware which need to know selected endpoint, should come after UseRouting but before UseEndpoints middleware. I will try to cover more about order of middleware in separate blogpost.

I hope this information was useful. Let me know your thoughts.

Leave a Reply