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

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.

主站蜘蛛池模板: 屏山县| 上思县| 山东| 汾西县| 东阳市| 神池县| 黑水县| 治多县| 双柏县| 咸丰县| 霍州市| 嘉祥县| 丰宁| 东城区| 页游| 枞阳县| 同江市| 荣成市| 封丘县| 邓州市| 康马县| 文成县| 贞丰县| 敖汉旗| 会泽县| 青田县| 波密县| 乌拉特中旗| 秦皇岛市| 昌图县| 文安县| 陈巴尔虎旗| 昌都县| 白银市| 且末县| 鄂托克旗| 邵阳县| 绥化市| 延庆县| 临江市| 惠东县|