Controller actions naming convention

点点圈 提交于 2019-12-08 17:20:49

问题


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.

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?


回答1:


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 }
);

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:

Routing by Action Name




回答2:


An alternative way is HTTP Methods attribute.

Instead of using the naming convention for HTTP methods, you can explicitly specify the HTTP method for an action by decorating the action method with the HttpGet, HttpPut, HttpPost, or HttpDelete attribute.

In the following example, the FindProduct method is mapped to GET requests:

public class ProductsController : ApiController
{
    [HttpGet]
    public Product FindProduct(id) {}
}

To allow multiple HTTP methods for an action, or to allow HTTP methods other than GET, PUT, POST, and DELETE, use the AcceptVerbs attribute, which takes a list of HTTP methods.

public class ProductsController : ApiController
{
    [AcceptVerbs("GET", "HEAD")]
    public Product FindProduct(id) { }
}



回答3:


This is one of those situations where following standards to the letter may not actually help you much.

One solution would be to allow yourself to deviate from the REST style.

You could have two get methods:

one could be GetByID, another could be GetByAge.

Your routes could look like this:

api/customer/getbyage/20 api/customer/getbyid/1134

This isn't exactly REST but it's close enough and one exception won't break anything.

My point is to use whatever implementation helps your product make sense and don't worry too much about standards.




回答4:


Restful services should not contain CRUD function names in the URI (https://restfulapi.net/resource-naming/)

this would more appropriate:

for GetById - http://mysite/api/customers/123

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



来源:https://stackoverflow.com/questions/33513580/controller-actions-naming-convention

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!