shou
shou

Reputation: 143

Controller actions naming convention

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?

Upvotes: 11

Views: 31476

Answers (4)

Nandun
Nandun

Reputation: 2042

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

Upvotes: 5

Andrei Dragotoniu
Andrei Dragotoniu

Reputation: 6335

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.

Upvotes: 2

Abou-Emish
Abou-Emish

Reputation: 2321

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

Upvotes: 3

Usman Khalid
Usman Khalid

Reputation: 3110

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

Upvotes: 5

Related Questions