Reviewing the API Controllers
In this lesson, we'll go through and review the API Controllers
Reviewing our controllers#
Now, as you can see here, we have some data as a part of the response. If you're following along, you'll see the same data here. We can see this response because we hit the WeatherForecast
endpoint.
You can see this beautifully managed because Swagger is taking care of this. As we discussed in the last lesson, Swagger is a documentation tool for our API. So all the endpoints we make in our project will be displayed on this page. You can run it or troubleshoot it. Currently, we only have one endpoint, weatherForecast
which comes bootstrapped with our Web API project. This was just a little overview of Swagger, but as mentioned, we will be using Postman
to test our endpoints.
Now let's go back to our code. You saw the response; now let's see why we saw what we saw. Inside the API project, we have a controllers
folder, and our controller folder has a WeatherForecastController
. Now you can guess where the weatherForecast endpoint came from. As we saw in the last lesson, we have Configure method which has a middleware called app.UseRouting()
. This middleware looks at the enpoint of the http request and sends it to the appropriate controller.
WeatherForecastController.cs
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace test.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
This page is a preview of The newline Guide to Fullstack ASP.NET Core and React