Updated March 30, 2023
Introduction to ASP.NET Core Routing
The following article provides an outline for ASP.NET Core Routing. ASP.NET Core Routing is nothing but a pattern matching method that categorizes the received requests and works out for those requests. In general, routing is the approach to provide a response for user requests. The routing is liable for matching received HTTP requests and transmits for those request to applications executable endpoints. Endpoints are nothing but the application’s executable code for request handling. Those endpoints are described and configured when the application starts initially. Then, the endpoint matching processes extract the values from the request URL and make available those values for processing the requests.
ASP.NET Core Routing Overview
Let’s assume the server is on right-hand side, and with the server, we have set up the ASP.NET Core Web Application. Inside the application, let’s have the controllers, and each of the controllers had contained with several action methods. On the left-hand side, there will be a user; it may be a Postman, Web Browser, Fiddler, Mobile Application, Swagger, and so on. Consider sending a request from a user to the browser; as seen already, the request will pass through the request process pipeline. Then, the ASP.NET Core Framework plot a route to the controller action method based on the relevant user’s action method to get the responses.
The essential thing is to realize how the application came to know which request is linked to which controller action method. In general, the mapping between the resource and the URL is called Routing.
Routing Basics
The basics of routing are representing the endpoints and connecting the incoming HTTP Request to the Controller action method. The namespace Microsoft.AspNetCore.Routing is liable to handle the requests and responses, connect the endpoints, inspect the requests, and modify the request and response messages that pass through the request process pipeline. The Routing is registered in the Middleware Pipeline of Startup.Configure.
Let’s see the following code for the basic routing example.
Code:
// the Configure () method called during the runtime
// to configure the HTTP Request pipeline by using this method
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("WELCOME TO APPS!");
});
});
}
The Routing used the middleware pairs which registered by UseEndpoints and UseRouting,
- UseEndpoints: It includes the endpoint execution to the middleware pipeline. It executes the delegate connected with the particular endpoint.
- UseRouting: It includes the route matching middleware pipeline. That middleware looks at a set of endpoints which described in the application and chooses the finest match based on the request.
Look at the single route code endpoint using the MapGet method in the above code.
The HTTP GET request sent to Root URL /:
The request delegate shown executes:
The WELCOME TO APPS is written to the HTTP response; by default, the URL root will be https://localhost:4005/.
If the request method is not GET then, it returns HTTP 404 and no route matches.
ASP.NET Core Routing EndPoints
The Endpoint Routing is a new feature included in ASP.NET Core that enables you to provide information about the routing to middleware in the request process pipeline. The endpoint routing matches the HTTP Request to the Endpoints in the middleware pipeline at the end. The Endpoint in ASP.NET Core is nothing but the URL of a resource.
The ASP.NET Core Endpoint are as follows:
- Executable contains a RequestDelegate.
- Extensible contains a MetaData Collection.
- Finally, Selectable contains the Routing Information.
- Finally, Enumerable is a collection of endpoints that can be listed by receiving the EndpointDataSource from DI.
ASP.NET Core Routing Concepts
In general, routing is the approach to give responses to user requests. The routing is answerable for matching received HTTP requests and transmitting those requests to applications executable endpoints. In ASP.NET Core Web Application, we can allow the Routing through the Middleware; for enabling the routing in ASP.NET Core, we must include the following two middleware components to process the HTTP request pipeline.
- UseRouting: This middleware allows you to enable the routing to the application; it will not enable to map of any of the URL to any resources. It includes the route matching middleware pipeline. Those middleware looks at a set of endpoints which described in the application and chooses the finest match based on the request.
- UseEndpoints: This middleware mapping the URL to the resources. The essential thing here is that not only to map the action methods, we need to map the static file resources to URL. We need to map the URL to action methods. It includes the endpoint execution to the middleware pipeline. It executes the delegate connected with the particular endpoint.
ASP.NET Core Routing Code
The ASP.NET Core Routing Code includes in various ways; they are as follows:
1. By using the attributes routing at controller level in ASP.NET core
Both the controller and action methods use the attribute routing; when we apply the routing attribute at the controller level, then the route is valid to the entire action methods of the controller. For example, look at the code below; in DefaultController class, the default route is used for several times by specifying the route template for action methods. The code snippet explains how to specify the routing template for action methods; it just explains how to specify the various routing attributes at the controller level to ease use in attribute routing.
Code:
[Route("Default")]
public class DefaultController : Controller
{
[Route("")]
[Route("Index")]
public ActionResult Index()
{
return new EmptyResult();
}
[HttpGet]
Route("Default/GetDetails_By_ID/{id}")]
public ActionResult GetDetails_By_ID (int id)
{
string str_data = string.Format("The Parameter ID is : {0}", id);
return Ok(str_data);
}
}
By using the routing attributes, the action and controller method levels the routing template applies at the controller level, which is pretended to routing template detailed at the action method.
2. By using the attribute routing at action method level in ASP.NET core
Look at the DefaultController Class; there will be three routings in the Index method of DefaultController Class. It involves each of the following URL invoking the Index() action method of the DefaultController method.
http://localhost:10223
http://localhost:10223/home
http://localhost:10223/home/index
In the conventional-based routing, we will specify the attributes-based routing parameters. In attribute-based routing, it enables you to specify the routing attribute with the parameters. The GetDetails_By_ID method of DefaultController class has explained earlier, in that “{id}” specifies the routing, which represents the parameter or the place holder.
Example of ASP.NET Core Routing
Let’s see the Routing Attributes in ASP.NET Core; by using the Routing Attribute, we describing that the routes in ASP.NET Core application either at the Action method or the Controller Method.
Let’s see the Routing Attribute signature as follows:
In this above, Route Attribute is the class inherited from the Attribute class and the IRouteTemplateProvider interface. The constructor of RouteAttribute takes the template as an input parameter thats the URL from the client, and it should not be null.
There will be a two-action method with the UserController class; just concentrate on the routing concept rather than the return type. We invoking the method GetAll_Users() with the URL /User/All and GetUser_ByID() method with the URL /User/ByID.
Code:
using Microsoft.AspNetCore;
namespace ASPNETCore_Routing.Controllers
{
public class UserController : ControllerBase
{
[Route("User/All")]
public string GetAll_Users()
{
return "Getting Response from GetAll_Users Method";
}
[Route("User/ByID")]
public string GetUser_ByID()
{
return "Getting Response from GetUser_ByID Method";
}
}
}
Finally, execute the application and access the method by using the URL we configured as shown below:
Output:
Conclusion
In this article, we have seen about the Routing technique in ASP.NET Core which provides us the perceptive framework to handle the URL’s and Endpoints. Routing represents the endpoints and maps of incoming requests to make use of routes.
Recommended Articles
We hope that this EDUCBA information on “ASP.NET Core Routing” was beneficial to you. You can view EDUCBA’s recommended articles for more information.