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

Matching route parameters

Remember that a template needs to have a controller token and an action token; these are the only required tokens and have special meaning. A controller will match a controller class and an action will match one of its public methods. Any other template parameter will match the parameter of the same name in the action method. For example, take a route with the following template:

{controller=Search}/{action=Query}/{phrase}

That route will map to this Querymethod in a class called SearchController:

public IActionResult Query(string phrase) { ... }
By convention, the name of the controller in a template does not take the Controller suffix.

If a route token is optional, then it must map to a parameter that has a default value:

{controller=Account}/{action=List}/{page?}

A matching method would have the following signature:

public IActionResult List(int page = 0)

Notice that the page parameter is an int instance that has a default value of 0. This might be used, for example, for paging, where the default page is the first one (zero-based). This would be the same as having a token with a default of 0 and mapping it to a parameter without a default value.

So far, we've only seen how we can map simple values of strings or basic types; we will soon see how we can use other types.

We've mentioned that the action parameter is required, but, although this is true in a way, its value may be skipped. In this case, ASP.NET Core will use a value from the HTTP action header, such as GET, POST, PUT, DELETE, and so on. This is particularly useful in the case of web APIs and is often very intuitive. So, for example, take a route with a template such as this:

api/{controller}/{id}

Say it has a request of this:

GET /api/Values/12

It can be mapped to a method such as this, in a controller named ValuesController:

public IActionResult Get(int id) { ... }

So, we just learned how template parameters are matched from templates to controller classes' methods. Now we will learn about dynamic routing, where the mapping is not pre-defined.

主站蜘蛛池模板: 上蔡县| 皮山县| 明溪县| 正定县| 大英县| 宜良县| 北票市| 遂川县| 绥宁县| 湘西| 田东县| 彰化县| 布尔津县| 秦皇岛市| 自治县| 香格里拉县| 襄汾县| 阿勒泰市| 辽阳市| 仁怀市| 隆林| 湘潭县| 开远市| 江油市| 改则县| 同仁县| 松原市| 徐汇区| 瓦房店市| 枞阳县| 措勤县| 灌阳县| 隆德县| 天气| 沙雅县| 忻州市| 漠河县| 日土县| 昌吉市| 德庆县| 吉林市|