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

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. 

主站蜘蛛池模板: 乐至县| 屏东县| 商都县| 杂多县| 湘潭市| 青阳县| 东海县| 南丰县| 九龙县| 新野县| 无锡市| 江口县| 乌兰察布市| 巴林右旗| 镇安县| 安顺市| 甘德县| 永安市| 浙江省| 木兰县| 利川市| 邻水| 昭觉县| 奎屯市| 双流县| 米林县| 大庆市| 凭祥市| 桂林市| 天柱县| 辽中县| 广元市| 仪陇县| 临泽县| 龙游县| 广灵县| 泽库县| 柳林县| 乌拉特后旗| 南城县| 山丹县|