Routing and Route Templates in ASPNET Core

This is a summary of the concepts of routing and route templates in asp.net core. We have taken a practical exercise to develop the concepts in an interesting way.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

A Simple Routing Project

Write a simple ASP.NET Core application (ignore security concerns) that receives a URL based GET request for a SELECT query. The pattern is /score/{course}/{roll}/{section}. The application should respond "Accepted" only if

  1. course is a regex match ^\d{3},
  2. roll is a number between 1000 and 2000,
  3. section is an alphabet string of any length.

Otherwise it should send a response code of 400 bad request.

What is Routing

  1. Routing matches incoming requests and dispatches them to their respective terminal endpoints where processing is done and response sent back to the client.
  2. This process can extract values from the URL.
  3. Routing is registered in the Startup.Configure method.
  4. Routing uses the middleware pair UseRouting and UseEndpoints.

Examples of Map Endpoints

Following are some of the extension methods on IApplicationBuilder that are used to map the requests:

MapGet, MapPost, MapDelete, MapPut, MapRazorPages (for razor pages), MapControllers (for controllers), MapHub (for SignalR), MapGrpcService (for gRPC)

What is a Route Template

In the following example /prod/{code} is a route template for the GET request.

app.UseEndpoints(endpoints =>
{

  endpoints.MapGet("/prod/{code}", async context =>
  {

    String pcode = context.Request.RouteValues["code"];

    await context.Response.WriteAsync($"{pcode}");

  });

});

Route Template Rules

  1. Tokens within {} define route parameters.
  2. Text matching is case-insensitive.
  3. Default values can also be specified. If nothing is specified, page is set to Home: {Page=Home}
  4. A nullable/optional can be specified with a question mark: {controller}/{action}/{id?}

Route Constraints

  1. id must be an int: {id:int}
  2. act must be a bool: {act:bool}
  3. similarly, datetime, decimal, double, float, guid, long are other constraints.
  4. name must be at least 4 characters long {name:minlength(4)}
  5. similarly, range, length, maxlength, min, max and alpha are other similar constraints.
  6. regex are also supported, but discouraged.

Solution to the Exercise

The configure method of the Startup class should be like this. Nothing else needs to be changed as obtained from the visual studio template.

public void Configure(IApplicationBuilder app)
{

  app.UseRouting();

  app.UseEndpoints(endpoints =>

  {

    StringBuilder sb = new StringBuilder();

    sb.Append("/score");

    sb.Append("/{course:regex(^\\d{{3}})}");

    sb.Append("/{roll:range(1000, 2000)}");

    sb.Append("/{section:alpha}");

    endpoints.MapGet(sb.ToString(), async context =>

    {

      HttpRequest req = context.Request;

      int course = Convert.ToInt32(req.RouteValues["course"]);

      int roll = Convert.ToInt32(req.RouteValues["roll"]);

      String section = Convert.ToString(req.RouteValues["section"]);

      // do whatever 
      await context.Response.WriteAsync("Accepted!");

    });

  });

  // any other request is bad 
  app.Run(async context =>

  {

    // bad request 
    context.Response.StatusCode = 400;

    await Task.CompletedTask;

  });

}

Comments and Discussion

Please write your comments and discussion on the following youtube video itself:


This Blog Post/Article "Routing and Route Templates in ASPNET Core" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.