A controller in ASP.NET Core is a file that contains a logical collection of actions that handle incoming URL requests through routes. Creating, understanding, and developing controllers and actions is discussed and demonstrated in this video.
- [Instructor] Now that we have NET framework set up in our project, I want to discuss controllers and actions. We briefly look at both during the attribute routing video, but I wanted to go into a little more detail for our web API implementation. We will also be looking at setting up data repositories that will handle the actual data CRUD calls to the database. It's a best standard I use with my API development, and I want you to learn it. Please know that I've added code for the data repositories in the exercise files for this video.
Implementing data repositories is really beyond the scope of this course, but we'll need them for the data cacheing. Let's go ahead and open up the project. Let's get back to controllers and what we need to know about them for web API development. By convention, in ASP.NET Core MVC, controller classes are located in the root level Controller folder, and inherit from microsoft.asp.netcore.mvc.controller.
These two conventions are not required, but I find staying within the coding convention, projects stay better organized. You also don't have to write any more code than you need to. Within the Model-View-Controller pattern, a controller is responsible for the initial processing of the request and creation of the model the controller works with. Remember in the previous video, Values controller worked with the Value model class. The controller takes the result of the model's creation and any code that runs in the model, and returns the proper result back to the API caller.
What we will have is our data repositories working with our models for abstraction purposes. Let's create the controller for the Customer model. Open up the Controller folder in the Solution Explorer. If there are any controller files that are created when you first set up the project, you can delete them. Right click on the Controllers folder and select Add and then New Item. To the right, you should see the Web API Controller Class template.
Highlight it and below, give CustomerController.cs for the file name. Press Add. You can see that the template not only created the controller class, but all the actions needed for the four HTTP verbs we will be using for our web API calls related to Customer. The controller and each action also have the needed attributes for routing. Great progress for our APIs.
Next we'll take a look at the data repositories and connecting them to our controllers.
- Installing Visual Studio and SQL Server
- Creating your Web API project
- Routing in ASP.NET Core
- Adding and connecting controllers
- Modeling binding and validation
- Measuring performance