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
-
course
is a regex match ^\d{3}, -
roll
is a number between 1000 and 2000, -
section
is an alphabet string of any length.
Otherwise it should send a response code of 400 bad request.
What is Routing
- Routing matches incoming requests and dispatches them to their respective terminal endpoints where processing is done and response sent back to the client.
- This process can extract values from the URL.
- Routing is registered in the Startup.Configure method.
- Routing uses the middleware pair
UseRouting
andUseEndpoints
.
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
- Tokens within {} define route parameters.
- Text matching is case-insensitive.
- Default values can also be specified. If nothing is specified, page is set to Home:
{Page=Home}
- A nullable/optional can be specified with a question mark:
{controller}/{action}/{id?}
Route Constraints
- id must be an int:
{id:int}
- act must be a bool:
{act:bool}
- similarly, datetime, decimal, double, float, guid, long are other constraints.
- name must be at least 4 characters long
{name:minlength(4)}
- similarly, range, length, maxlength, min, max and alpha are other similar constraints.
- 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.