ASP.NET MVC API Web Controller

{title}

Working with the separation of the layers of an application leaves us the breadth and freedom to build different sections to build the flow of our site. Data services are one of these possibilities, instead of building countless controllers to access the different actions, we can build data services that can be called from anywhere in the application itself.
To achieve this we will need different controllers, these are not necessarily very different from traditional controllers, but they have certain differences that characterize them, one of these differences is their location within our project.

Generate a Web API Controller


A Web API controller is a controller of our application that allows us to use its methods and actions via AJAX, this allows us to build sections of our application that we can reuse in different contexts.
How does it help us?

This tool then helps us reduce the amount of code we build, making it possible to program something that is easier to maintain and debug, giving us a cleaner and more modern project.
As in the ASP.NET MVC applications it is necessary to work based on conventions, the first thing we must decide is where our new Web API controller will reside, this location is indifferent to its operation, but it can help us in the future to improve the order of our project.
Suppose then that we have decided to create a folder called Api at the root of our application, once created this folder we will right click with our mouse on it and we will create a controller, we must choose the option API Controller with actions of Empty reading and writing, we choose a unique name for that controller, since being visible throughout the project can have conflicts with other controllers of the same name.
Let's see in the following image how we create the driver file.

{title}


We note then that the action to generate our new controller is very similar to the generation of a normal controller.

Content


As we are building a new service, this will be handled with standard HTTP methods, these are GET, POST, DELETE and PUT, since this is the norm our controller must handle each of these cases, therefore if we see the Our controller content will have something similar to the following:

{title}


We see then that we have an empty standard action with each of the HTTP methods mentioned and if we are even more observant we will see that the only one that returns a value by default is the GET method, which is the default query method.
Advantage

When working directly with HTTP methods, we can then use jQuery, for example, to make AJAX calls to our new controller using any of these methods, so an AJAX call via GET will give us the content of what we have placed in our controller in the method GET that is created by default.

  • 0