- Hands-On Full:Stack Web Development with ASP.NET Core
- Tamir Dresher Amir Zuker Shay Friedman
- 287字
- 2021-06-10 19:37:29
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()
{
...
}
- 物聯(lián)網(wǎng)與北斗應(yīng)用
- C++黑客編程揭秘與防范
- 物聯(lián)網(wǎng)安全與深度學(xué)習(xí)技術(shù)
- 網(wǎng)絡(luò)創(chuàng)新指數(shù)研究
- 物聯(lián)網(wǎng)安全技術(shù)
- Yii Application Development Cookbook(Second Edition)
- Unity Artificial Intelligence Programming
- 光纖通信系統(tǒng)與網(wǎng)絡(luò)(修訂版)
- 物聯(lián)網(wǎng)場(chǎng)景設(shè)計(jì)與開發(fā)(初級(jí))
- 5G非正交多址接入技術(shù):理論、算法與實(shí)現(xiàn)
- bash網(wǎng)絡(luò)安全運(yùn)維
- Guide to NoSQL with Azure Cosmos DB
- 物聯(lián)網(wǎng)與智慧農(nóng)業(yè)
- 網(wǎng)絡(luò)基本通信約束下的系統(tǒng)性能極限分析與設(shè)計(jì)
- 網(wǎng)絡(luò)空間作戰(zhàn):機(jī)理與籌劃