Controller actions naming convention

2019-06-21 17: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?

3条回答
▲ chillily
2楼-- · 2019-06-21 18:18

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.

查看更多
狗以群分
3楼-- · 2019-06-21 18:32

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

查看更多
放荡不羁爱自由
4楼-- · 2019-06-21 18:35

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) { }
}
查看更多
登录 后发表回答