Routing constraints

Routing constraints are part of the templating routing system of ASP.NET Core. They provide a way for us to match a route with a parameter type or a set of values, like so:

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller}/{action}/{id:guid?}");
});

In this case, our route template will match all the https://myhostname/mycontroller/myaction calls and all the calls that present a valid Guid as an id parameter, for example, https://myhostname/mycontroller/myaction/4e10de48-9590-4531-9805-799167d58a44. The {id:guid?} expression gives us two pieces of information about constraints: first, the parameter must have the guid type, and secondly, it is specified as optional using the ? character. ASP.NET Core provides a rich set of built-in routing constraints such as min and max valuesregular expressions, and range. It is also possible to combine them using the colon operator (:), like so:

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller}/{action}/{id:int:min(1)}");
});

In this case, we are combining the int constraint with the min(1) constraint. Therefore, we can cover a large number of use cases and business rules. In addition, we can improve our routing matching logic by providing different action methods for the same URI that is receiving a different type of data. It is also important to note that the same routing constraints can also be applied to the attribute routing part:

    [Route("api/mycontroller")]
[ApiController]
public class MyControllerController : ControllerBase
{
[HttpGet({id:int:min(1)})]
public IActionResult Get() {
...
}

ASP.NET Core provides a rich set of default routing constraints that can be used out of the box. The following link lists all the additional default routing constraints of ASP.NET Core: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-3.0#route-constraint-reference

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.93.210