How to use route constraints in ASP.NET Core minimal APIs

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.
TNG – Latest News & Reviews
