Everything You Should Know About ASP .NET Core Routing
.NET Core Web App Routing Templates, Parameters and Attributes

Everything You Should Know About ASP .NET Core Routing

In this article, we are going to see three different ways to setup routing in ASP .NET Core web application.

Route Templates

Let’s switch back to basic code sample. The sample where Startup.cs defines two endpoints. If you notice, the second endpoint is defined by using template /{name}.

This template instructs framework that first token in URL after hostname should be available in a route parameter. The code sample also shows how to read the route parameter value.

We can specify multiple route parameters as long as there is at least one literal character.

e.g. {name}{id} is not a valid route template as two routing parameters do not have any literal character specified in between. But {filename}.{extension?} is a valid routing template as two tokens are separated by literal character dot. Also question mark means he token is optional

The literal text between two route parameters must exactly match the incoming URL.

We might be wondering how this is related to .NET core web application’s routing. But it is the first basic that we should know. Routing template defines how URLs would be used by routing middleware to identify the endpoints.

What can be specified in route template ?

With every routing template, we can specify:

  • Some route parameters e.g. {controller}/{action} means controller name followed by action name in .NET core MVC or web API application.
  • Some optional parameters e.g. {filename}.{extension?} means extension is optional
  • Some patterns or regex or data type or length to make make strict matching e.g. {id:int} specifies that id router parameter should be integer.
  • Some catch all tokens which are prefixed by asterisk (*) or two asterisks(**).
  • Some router parameters might have default values specified

So I can specify a path like this to accept username, filename and price in the URL. If you want to know more about routing templates and parameters and constraints, please refer this page from the documentation.

{username:minlength(4)}/{filename:maxlength(8)}/{price:decimal}

Common Route Params

There are some route parameters which are identified by framework, e.g. controller, or action are most common templates that you can find in MVC or Web API project’s routing.

The controller token in routing template would take the token from actual incoming URL and would find if there is any controller with that name.

Similarly, the action token from routing template would try to find the action inside the selected controller with same name. The incoming request would be handed over to the action only if HTTP verb from incoming requests match with allowed HTTP verbs for the action.

e.g. if routing template is {controller=Home}/{action=Index} then a GET to “/” would be handed over to Index action inside Home controller, provided GET verb is allowed for that action.

There are other route parameters too, you can read the documentation for more info.

Middleware Configurations

Many of you might be aware of the fact that a basic routing template can be specified for .NET Core web application (MVC) in Startup.cs as shown below.

There are various methods provided by ASP .NET Core framework can be used to configure routing templates in startup. Some of the methods are:

Below is a sample code showing how routing is configured in ASP .NET MVC .NET core web application’s template.

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Register service to add all controllers and views for routing
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// some middlewares
app.UseRouting();
// some more middlewares
app.UseEndpoints(endpoints =>
{
// Routing template
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
// Above is same as calling below method
// endpoints.MapDefaultControllerRoute()
});
}
}
view raw Startup.cs hosted with ❤ by GitHub

Route Attributes

Routing can also be configured using Route attribute. This attribute can either be placed on controller class or on every individual method. This attribute takes route parameters as string input. The tokens like [controller] or [action] can be used in route template.

All controllers marked with ApiController attribute are required to use attribute based routing.

Http Attributes

ASP .NET Core web application also provides a way to define the verbs that can be accepted by an action. This can be defined by placing an HTTP verb attribute on the action.

.NET provides various HTTP verb attributes and each attribute can accept route as a parameter. Below code snippet shows how a GET action can accept a parameter from URL.

Below code template shows both Route attribute and HttpGet attributes and how they are used to specify routing parameters.

[Route("api/[controller]")]
[ApiController]
public class ValuesController1 : ControllerBase
{
// GET: api/Values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/Values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/Values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/Values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/Values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
view raw ValuesController.cs hosted with ❤ by GitHub

I hope this information was helpful to bring some clarity about how routing can be configured in .NET web applications. If you have any suggestions / feedback, let me know your thoughts.

Leave a Reply