控制器动作命名约定

sho*_*hou 7 c# naming-conventions asp.net-web-api asp.net-web-api-routing

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

所以,如果我想让网址用户友好,比如"api/customer /",我也想按照动作命名约定,比如Get(int id)/ Get(int age),我该怎么做?

Usm*_*lid 6

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

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

然后你可以发出GET请求

http://mysite/api/customer/GetCustomerById/1
Run Code Online (Sandbox Code Playgroud)

另外,我建议你学习下面的文章,以便更深入地理解:

按操作名称路由

  • 这个答案有误导性,REST应该在HTTP方法中使用路径和动词中的名词,即GET/api/customers/1.更多细节:https://martinfowler.com/articles/richardsonMaturityModel.html (6认同)

Nan*_*dun 5

Restful 服务不应在 URI 中包含 CRUD 函数名称 ( https://restfulapi.net/resource-naming/ )

这会更合适:

对于 GetById - http://mysite/api/customers/123

对于 GetByAge -http://mysite/api/customers?age=21