Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 636
shou Avatar asked Nov 04 '15 04:11

shou


People also ask

How do you name a controller method?

Controllers should be in singular case, no spacing between words, and end with "Controller". Also, each word should be capitalised (i.e. BlogController, not blogcontroller). For example: BlogController , AuthController , UserController .

What are naming conventions examples?

What is an example of a good naming convention? Good naming examples include: [Project number] - Data Use Agreement - [Title of research project] Approval - Change to employee travel policy - February 2014.

What are the naming convention MVC?

MVC conventions have Controllers in one directory and Views belonging to the Controller in a Views sub-directory with the same name as the Controller. For example, for the HomeController we will expect to find its Views in /Views/Home or /Views/Shared directories.

What are controller actions?

An action (or action method) is a method on a controller which handles requests. Controllers logically group similar actions together. This aggregation of actions allows common sets of rules, such as routing, caching, and authorization, to be applied collectively. Requests are mapped to actions through routing.


1 Answers

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

like image 169
Usman Khalid Avatar answered Sep 25 '22 17:09

Usman Khalid