This video is available to students only

Adding our First Controller

In this lesson, we'll add our first controller which will get us data from our database

Adding our first Controller#

We have successfully seeded the data in our database and we can see it in our table. Now we want to query the database and for that, we will have to write our Controller. First of all, let's open the API project and check what's going on inside the WeatherForecast Controller. In this project, we are going to create many controllers. All of them will derive from the ControllerBase and will share similar attributes such as APIController attribute and Route attribute with controller placeholder. Since we are sharing this part in all our controllers, rather than repeating ourselves in each controller, let's create a BaseController which will include all of this, and we will derive from that.

Let's create a new class and name it BaseController. As mentioned earlier, we will derive it from ControllerBase which is the same we saw inside the WeatherForecastController. Let's use quick fix and import it from Microsoft.AspNetCore.Mvc; step one is done. Let's also use both of the common attributes above this; ApiControllerAttribute and the RouteAttribute with api/controller placeholder, since we want our endpoints to start with Api route. This placeholder will be replaced with the name of the class which we are going to name CoursesController and the route will be called api/courses. Let's create the class now. Right click on the controller folder and click on new class; we are going to call it CoursesController. Now let's derive it from the BaseController we just created.

BaseController.cs:

We will be using services inside the controller for which we'll have to create a constructor. Let's put the cursor on CoursesController and use quick fix. Choose GenerateConstructor CoursesController. Our constructor is now ready. To query our database, we need StoreContext here. This is not going to be part of our architecture, but for the time being, let's call the StoreContext here, context. Let's bring it using Infrastructure. To make it available for our methods, let's go to context and using quick fix; we can then select Initialize field using parameter. I am telling you again that this practice is not recommended, we are doing it just for the time being. We will abstract the database using Repository pattern in the future lessons. We are using this method just for demonstration purpose.

Start a new discussion. All notification go to the author.