ASP.NET Core Routing - A Step-by-Step Tutorial

Routing is the process of matching incoming HTTP requests with the appropriate action method in the controller. In ASP.NET Core, the routing system has been redesigned to be more flexible, extensible, and easier to use. In this article, we will discuss what routing is, how it works, and how to implement routing in ASP.NET Core.

ASP.NET Routing

What is Routing?

Routing is the process of mapping a URL to an action method in the controller. The routing system looks at the incoming request's URL and matches it to a set of predefined patterns to determine which controller action method should handle the request. The pattern matching process is called route matching.

For example, consider the following URL:

https://www.dotnet4techies.com/Product/Details.aspx?id=100

The above URL includes a query string parameter, which can make it difficult to read and understand the content of the page. With ASP.NET Core Routing, we can create a more user-friendly and easier to remember URL, like below:

https://www.dotnet4techies.com/Product/100/Microsoft-surface-pro9

In the above URL, we have used routing to map the product ID to a specific product page, making the URL more readable and user friendly.

How does Routing work?

ASP.NET Core Routing works by intercepting incoming requests and mapping them to specific handlers or actions in the application. When a user makes a request for a specific URL, the routing engine analyzes the URL and attempts to match it with a defined route pattern.

A route pattern consists of a URL pattern and a set of constraints. The URL pattern defines the structure of the URL, while the constraints specify the valid values for each URL segment.

For example, consider the following route pattern:

{controller}/{action}/{id}

This route pattern specifies that the URL should consist of three segments, separated by slashes. The first segment represents the controller, the second segment represents the action, and the third segment represents the ID (in our above previous URL, Product ID)

ASP.NET Routing then maps the incoming request URL to the appropriate controller, action, and ID.

For example, the following URL:

https://www.dotnet4techies.com/Product/Details/100

It would be mapped to the Product controller, the Details action, and the ID 100.

Implement Routing in ASP.NET Core

Now that we understand how ASP.NET Routing works, let's see how to implement it in our web application.

The ASP.NET Core routing system is based on middleware. Middleware is a software component that handles HTTP requests and responses. When a request comes into the ASP.NET Core application, it is first processed by middleware that handles the request's routing.

If you would like to know more about what exactly the Middleware Pipeline in ASP.NET Core, then you must read below two topics:


Create custom middleware in ASP.NET Core 

The routing middleware looks at the incoming request URL and matches it to a set of predefined patterns. The patterns are defined in the route table, which is a collection of route objects. Each route object defines a URL pattern and the corresponding controller and action method that should handle the request.

Once a match is found, the routing middleware passes the request to the corresponding controller action method, which then processes the request and returns a response.

Step 1: Configure Route pattern

The first step is to define the route configurations in the startup called, program.cs file. Here is an example of defining route configuration.

[pre class="brush:csharp; toolbar: false;" title=""] //configure route pattern for produt details app.MapControllerRoute( name: "ProductDetails", pattern: "product/{id}/{productName}", defaults: new { controller = "Product", action = "Details" } ); [/pre]
The above route configuration maps the URL https://www.dotnet4techies.com/Product/100/Microsoft-surface-pro9 to the Details action in the ProductController. The {id} in the URL is a placeholder that will be replaced with the actual product ID, and {productName} in the URL is replaced with actual product Name.

Step 2: Enable Routing

Now enable the routing via your application middleware pipeline. You will need to add the below code in your program.cs to enable the routing for your application.

[pre class="brush:csharp; toolbar: false;" title=""] //enable routing app.UseRouting(); [/pre]

Step 3: Create Controllers and Actions

The final step is to create controller and action that correspond to the route configurations defined in step 1.

Since we defined a route configuration for the Product controller that maps the product ID and product Name to the Details action. We can create the ProductController and the Details action as below:

[pre class="brush:csharp; toolbar: false;" title=""] public class ProductController : Controller { public IActionResult Details(int id, string productName) { //get the product details from your database Product product = _db.GetProduct(id); //if product name from db not matches to URL product name, then redirect to correct url if (product.Name != productName) { return RedirectToActionPermanent("Details", "Product", new { id = id, productName = product.Name.Replace(" ", "-") }); } //send the product details to view return View(product); } } [/pre]
In the above example, the Details action takes an id and productName parameters that corresponds to the product ID and product Name in the URL.

Inside the Details action, we retrieve the product details from the database using the id parameter.

We then compare the productName parameter in the URL to the actual product name retrieved from the database. If the names don't match, we redirect the user to the correct URL using the RedirectToActionPermanent method.

Finally, we then pass the product details to the View to render product details to user.

Conclusion

In this article, we explored URL routing in ASP.NET Core and learned how to implement it in your web application. We covered the three main steps to implement ASP.NET Core routing by defining route configurations, enabling routing, and creating controllers and actions that correspond to the route configurations.

By following these steps, developers can create user friendly URLs that are easy to read and understand for both users and search engines.

Happy coding!!

No comments:

Powered by Blogger.