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),我该怎么做?
如果希望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)
另外,我建议你学习下面的文章,以便更深入地理解:
Restful 服务不应在 URI 中包含 CRUD 函数名称 ( https://restfulapi.net/resource-naming/ )
这会更合适:
对于 GetById -
http://mysite/api/customers/123
对于 GetByAge -http://mysite/api/customers?age=21
归档时间: |
|
查看次数: |
14800 次 |
最近记录: |