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

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. 

主站蜘蛛池模板: 昌乐县| 化德县| 伊通| 德格县| 涞水县| 香港| 东平县| 聂拉木县| 南郑县| 蒲江县| 衡阳市| 垦利县| 乌鲁木齐市| 板桥市| 石门县| 鸡西市| 龙山县| 黔东| 宝兴县| 衡山县| 石嘴山市| 金乡县| 游戏| 平湖市| 醴陵市| 石林| 五河县| 雅江县| 隆化县| 旌德县| 新乡市| 杭锦后旗| 溧阳市| 尉氏县| 乃东县| 达尔| 香港 | 潍坊市| 禄劝| 漾濞| 华蓥市|