Creating an API controller for questions

Let's create a controller for the api/questions endpoint. If we don't have our backend project open in Visual Studio, let's do so and carry out the following steps:

  1. In Solution Explorer, right-click on the Controllers folder, choose Add, and then Class....
  2. In the left-hand panel, find and select ASP.NET Core and then API Controller Class in the middle panel. Enter QuestionsController.cs for the name of the file and click Add:

  1. If the generated class doesn't inherit from ControllerBase, let's add this and remove the example action methods:
public class QuestionsController : ControllerBase
{

}

ControllerBase will give us access to more API-specific methods in our controller.

  1. If the generated class isn't decorated with the Route and ApiController attributes, let's add them:
[Route("api/[controller]")]
[ApiController]

public class QuestionsController : ControllerBase
{

}

The Route attribute defines the path that our controller will handle. In our case, the path will be api/questions because [controller] is substituted with the name of the controller minus the word controller.

The ApiController attribute includes behavior such as automatic model validation, which we'll take advantage of later in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.171.246