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

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. 

主站蜘蛛池模板: 华蓥市| 江阴市| 漠河县| 阳原县| 昆山市| 东乌| 遵义市| 葫芦岛市| 台南县| 德保县| 东乡| 汤原县| 江津市| 都安| 巴林左旗| 永胜县| 芷江| 锡林郭勒盟| 盐亭县| 同德县| 扶余县| 原阳县| 新田县| 郎溪县| 抚顺市| 铁岭市| 松桃| 商南县| 收藏| 曲麻莱县| 宝兴县| 炎陵县| 郓城县| 罗源县| 印江| 邛崃市| 老河口市| 阿拉善右旗| 揭阳市| 德兴市| 民和|