Navigation
Recherche
|
How to use route constraints in ASP.NET Core minimal APIs
jeudi 26 juin 2025, 11:00 , par InfoWorld
![]() In an earlier post here, we discussed how to work with route constraints when building controller-based APIs in ASP.NET Core Web API. In this post we will examine how we can work with route constraints when building minimal APIs. To use the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here. What is a route constraint? Why is it needed? A route constraint in ASP.NET Core is a guardrail for the URL. It is a mechanism that enables you to determine, in plain terms, whether an incoming request matches predefined criteria and should be processed. Route constraints in ASP.NET Core are used to filter out unwanted requests or prevent invalid data from reaching your controller actions. You can take advantage of the set of classes available as part of the Microsoft.AspNetCore.Routing.Constraints namespace to define route constraints. You typically combine multiple constraints when defining your application’s routing configuration. For example, you may want to define a route constraint that allows only positive integers in the route parameter. You may also want to enforce a specific length for a route parameter. By ensuring that only requests that match your specific criteria are actually processed by your action methods, route constraints improve the security and performance of your application. Plus, route constraints provide a cleaner and simpler way to filter requests than having to write boilerplate and complex code. In other words, they also help to make your application easier to maintain. Create an ASP.NET Core Web API project in Visual Studio 2022 To create an ASP.NET Core Web API project in Visual Studio 2022, follow the steps outlined below. Launch the Visual Studio 2022 IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences. Click Next. In the “Additional Information” window shown next, select “.NET 9.0 (Standard Term Support)” as the framework version and ensure that the “Use controllers” box is unchecked since we’ll be using Minimal APIs in this project. Elsewhere in the “Additional Information” window, leave the “Authentication Type” set to “None” (the default) and make sure the check boxes “Enable Open API Support,” “Configure for HTTPS,” and “Enable container support” remain unchecked. We won’t be using any of those features here. Click Create. We’ll use this ASP.NET Core Web API project to work with the REPR (request-endpoint-response) design pattern in the sections below. Applying route constraints in minimal APIs Route constraints can be applied in either of two ways: Using an inline constraint by specifying a constraint parameter in the MapControllerRoute method. Using a route attribute in the controller or any of its action methods. Use an inline constraint to apply route constraints The following code snippet shows how you can apply a route constraint in the MapControllerRoute method. endpoints.MapControllerRoute( name: 'default', pattern: 'controller=Home}/{action=Index}/{id:int?}'); Use route parameters to apply route constraints You can leverage route parameter constraints to specify rules for your route parameters using the following syntax. {parameter:constraint} The following code snippet illustrates how you can enforce that a parameter must be an integer or match a specific pattern. app.MapGet('/orders/{id:int}', (int id) => $'Order Id: {id}'); Using route constraints for low-level validations You can apply route constraints to perform low-level validations in minimal APIs. We’ll examine how this can be achieved in this section. Applying a route constraint in the MapController method Let us first use inline constraints to perform the validation. The following code snippet shows how you can use the MapControllerRoute method to apply a route constraint on your endpoint. In this case, the constraint requires that the author Id be an integer. app.MapControllerRoute( name: 'onlyInteger', pattern: 'author/{id:int}', defaults: new { controller = 'Author', action = 'Author Details' }); Similarly, you can specify that the firstname parameter for the /author endpoint must have a length greater than or equal to three, meaning that thefirstname of an author must contain a minimum of three characters. The following code snippet illustrates how you can specify this in your endpoint as a route constraint. app.MapControllerRoute( name: 'nameLength', pattern: 'author/{firstname:minlength(3}', defaults: new { controller = 'Author', action = 'Get Author'}); Applying a route constraint in the MapGet, MapPut, and MapPost methods Next we’ll examine how we can perform the validation using route parameter constraints. Consider the following C# class named Author. public class Author { public int AuthorId { get; set; } public string FirstName { get; set; } = string.Empty; public string LastName { get; set; } = string.Empty; public string Address { get; set; } = string.Empty; public string Email { get; set; } = string.Empty; public string Phone { get; set; } = string.Empty; } The following code snippet shows how you can retrieve data from the HTTP GET endpoint route /authors/{authorId:int}. app.MapGet('/authors/{id:int}', (int id) => $'Author Id: {id}'); Similarly, the following HTTP POST endpoint accepts an author Id and the count of books written by the author and returns a text message. app.MapPost('/author/{authorId:int:min(1)}/books/{count:int:min(1)}', (int authorId, int count) => $'Author with Id {authorId} has written {count} books.'); As shown in the preceding code example, both the authorId and the count parameters should have a minimum integer value of 1. The code snippet below shows how you can use the HTTP PUT endpoint to update the count of books authored by an author identified by authorId, taking advantage of the route parameter constraint illustrated above. app.MapPut('/author/{authorId:int:min(1)}/books/{count:int:min(1)}', (int authorId, int count) => $'Author with Id {authorId} has written {count} books.'); Example of a route constraint in action Finally, let’s examine how we can specify route constraints when passing objects and primitive data types (char, int, etc.) as parameters. Consider the following HTTP POST endpoint, which adds a new author and the number of books authored to a database. app.MapPost('/authors/{count:int:min(1)}', (Author author, int count) => Results.Ok($'1 new author record of an author who has written {count} ' + $'books has been added to the database...') ); Let’s invoke this endpoint using Postman. We’ll send the following JSON data for our new author in the body of the request. { 'authorId': '1', 'firstName': 'Joydip', 'lastName': 'Kanjilal', 'address': 'Hyderabad, India', 'email': 'joydipkanjilal@yahoo.com', 'phone': '1234567890' } Our route constraint requires us also to specify the count of books written by the author in the URL. Further, it requires that the count be a minimum integer value of 1. Figure 1 shows the output in Postman when we pass a count of 5. Figure 1. Success! Invoking the HTTP POST endpoint in Postman is successful because the route constraint for the count parameter has been satisfied. Foundry Let’s see what happens when we violate the route constraint. Figure 2 shows the output in Postman when we pass a count parameter of 0. Note that if we specify a value less than 1 for the count parameter, a HTTP 404 error will be returned in the response. Figure 1. Oops. Invoking the HTTP POST endpoint in Postman results in a 404 Not Found error because the route constraint for the count parameter has been violated. Foundry Not for data validation Keep in mind that you should not use route constraints for input data validation. If your endpoints contain route constraints that validate input data, an invalid input will return a 404 Not Found response, not a 400 Bad Request response. Remember, the purpose of route constraints is to disambiguate similar routes (i.e., to help ASP.NET Core efficiently resolve requests), not to validate the input data for your route. You can also take advantage of custom route constraints in ASP.NET Core to validate route values and avoid passing unwanted or unnecessary requests to action methods. You can refer to Microsoft’s documentation to learn about all of the supported route constraints.
https://www.infoworld.com/article/4011299/how-to-use-route-constraints-in-asp-net-core-minimal-apis....
Voir aussi |
56 sources (32 en français)
Date Actuelle
mar. 1 juil. - 05:34 CEST
|