Controller actions naming convention

shou picture shou · Nov 4, 2015 · Viewed 20.7k times · Source

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?

Answer

Usman Khalid picture Usman Khalid · Nov 4, 2015

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