官术网_书友最值得收藏!

Attribute-based routing

Attribute-based routing allows you to control the exact route that each controller and action takes part in by using the attributes that decorate your controllers and methods. I recommend that you use this approach for most of your APIs, since it will make your code more explicit and reduce routing errors that might be introduced as you add more controllers and actions.

At the beginning of this chapter, we created the ProductsController, which looked like this:

[Route("api/Products")]
[ApiController]
public class ProductsController : Controller
{
...
}

The RouteAttribute attribute that decorates the ProductController contains the URL template that maps to this controller. In this case, every request with a URL prefixed with /api/products/ will be routed to this controller. You can use the RouteAttribute attribute on controllers and on methods, but for methods, it's recommended to use the Http[Verb]Attribute attribute, where [Verb] is one of the standard HTTP verbs (Get, Post, Put, Delete, and so on).

The Http[Verb]Attribute and RouteAttribute attributes can be assigned multiple times to define multiple routes, and are hierarchical, which means that they support route inheritance. This means that if you configured a route on your controller, the routes you define on the methods will extend it.

For example, here is how you can configure that the ProductsController.GetProducts method will be mapped to a HttpGet request to the URL /api/products/all, in addition to the URL /api/products:

[HttpGet]
[HttpGet("all")]
public string[] GetProducts()
{
...
}
If the Http[Verb]Attribute that you set on a method contains a string that begins with /, then it won't be combined with the route defined in the controller, and will instead define a route of its own.
主站蜘蛛池模板: 任丘市| 平谷区| 花莲县| 海伦市| 永年县| 忻州市| 中江县| 泰安市| 佳木斯市| 清远市| 桂林市| 万安县| 昔阳县| 东源县| 茌平县| 格尔木市| 达孜县| 襄樊市| 定安县| 闸北区| 儋州市| 乐陵市| 芦山县| 广西| 翁源县| 噶尔县| 德阳市| 内江市| 刚察县| 澜沧| 横山县| 绥阳县| 乐亭县| 巨鹿县| 收藏| 六枝特区| 遵义县| 井冈山市| 阜南县| 东乌珠穆沁旗| 南丰县|