控制器动作命名约定

控制器动作命名约定

问题描述:

如命名约定所述,WebApi控制器动作名称应为Get(),Put(). Post()等.但是请告诉我,如果我有一个控制器为 CustomerController ,现在我想在其中执行两个操作.一个是 GetCustomerById(int id),另一个是 GetCustomerByAge(int age).这两个动作都将一个参数接受为int.

As naming convention says, WebApi controller actions name should be Get(), Put(). Post() etc. But tell me if I have a controller as CustomerController, now I want to have two actions inside of it. One is GetCustomerById(int id) and another one is GetCustomerByAge(int age). Here both the actions accept one parameter as int.

因此,如果我想使url用户友好(如"api/customer/" ),我也想遵循操作命名约定,例如仅 Get(int id)/Get(年龄),我该怎么做?

So, if I want to make the url user friendly like "api/customer/" also I want to follow the actions naming convention like only Get(int id)/Get(int age), how will I do it?

如果您希望Web Api在路由时查找操作名称,请将App_Start文件夹中的WebApiConfig.cs类更改为以下名称:

If you want Web Api to look for the action name when routing, change the WebApiConfig.cs class in the App_Start folder to below:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

然后您可以向GET请求

Then you can just make a GET request to

http://mysite/api/customer/GetCustomerById/1

此外,我建议您研究以下文章以加深了解:

Also I recommend you to study the article below for deeper understanding:

按操作名称进行路由