Understanding controllers

Web API resources are implemented using controllers. Let's have a look at the controller the template project created by opening WeatherForecastController.cs. This contains a class called WeatherForecastController that inherits from ControllerBase with a Route annotation:

[ApiController]
[Route("[controller]")]

public class WeatherForecastController : ControllerBase
{
...
}

The annotation specifies the web API resource URL that the controller handles. The [controller] object is a placeholder for the controller name, minus the word Controller. This controller will handle requests to weatherforecast.

The method called Get in the class is called an action method. Action methods handle specific requests to the resource for a specific HTTP method and subpath. We decorate the method with an attribute to specify the HTTP method and subpath the method handles. In our example, we are handling an HTTP GET request to the root path (weatherforecast) on the resource:

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
...
}

Let's have a closer look at the web API at runtime by carrying out the following steps:

  1. Run the app in Visual Studio by pressing F5.
  2. When the app has opened in our browser, press F12 to open the browser developer tools and select the Network panel.
  3. Select the Fetch data option on the top navigation bar. An HTTP GET request to weatherforecast will be shown:

  1. An HTTP response with a 200 status code is returned with JSON content:

If we look back at the Get action method, we are returning an object of the IEnumerable<WeatherForecast> type. The MVC middleware automatically converts this object into JSON and puts it in the response body with a 200 status code for us.

So, that was a quick look at the backend that the template scaffolded for us. In the next section, we'll walk through the React frontend.

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

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