Custom attribute routing

The routing engine of ASP.NET Core also provides a way for us to create our routing attributes. This technique is useful in complex routing systems where it is essential to keep a conceptual order between different routes. An example of a custom routing definition is as follows:

using System;
using Microsoft.AspNetCore.Mvc.Routing;

namespace SampleAPI.CustomRouting
{
public class CustomOrdersRoute : Attribute, IRouteTemplateProvider
{
public string Template => "api/orders";

public int? Order { get; set; }

public string Name => "Orders_route";
}
}

The class extends the Attribute abstract class, which is to be applied as an attribute. It implements IRouteTemplateProvider to get the attributes of the routing template workflow. As a result, the application of the attribute looks as follows:

[CustomOrdersRoute]
[ApiController]
public class OrderController : ControllerBase
{
...

This approach is really useful when we want to implement a more complex routing system. Therefore, it is possible to apply concepts such as inheritance to improve the reusability of the implemented routing rules.

This section provided an understanding of different routing approaches of ASP.NET Core: conventional routing and attribute routing. In the next section, we will discover how to use the routing constraints rules provided by the framework.

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

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