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

Parameterizing the route template

Attribute-based routing supports a few predefined tokens that are placed in square brackets ([ and ]), and will be replaced at runtime with their corresponding value:

  • [controller]: This will be replaced with the controller name.
  • [action]: This will be replaced with the method name.
  • [area]: If your application supports areas, this will be replaced with the area in which the controller resides. Area functionality is not covered in this book, but for more information, you can refer to https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/areas.

For example, instead of writing ProductsController explicitly in the RouteAttribute, we can write it like this:

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

Tokens within curly braces ({}) define route parameters that will be bound to the method parameters if the route is matched.

For example, suppose you wish to expose an API to search for products, based on a keyword, in the form of a GET request to a URL formatted as /api/products/search/keyword. This is how you can write it:

[HttpGet("search/{keyword}")]
public string[] SearchProducts(string keyword)
{
...
}

Just like with conventional routing, you can define default values and constraints on the route parameters. 

主站蜘蛛池模板: 合作市| 合山市| 北票市| 韶关市| 温泉县| 饶阳县| 福州市| 剑川县| 尉氏县| 驻马店市| 天门市| 盱眙县| 潞城市| 长顺县| 赤壁市| 林芝县| 将乐县| 嘉峪关市| 东方市| 乐清市| 凤山市| 安阳市| 泰顺县| 临湘市| 北川| 揭东县| 临洮县| 新巴尔虎左旗| 宜阳县| 汶川县| 兴隆县| 郸城县| 曲松县| 城市| 浦东新区| 汶上县| 德保县| 长治县| 育儿| 北川| 山阳县|