Understand controller

ASP.NET Core Web API Controllers

Here's the code for the entire WeatherController class. Don't worry if it doesn't make sense yet. We'll go through it step by step.

using Microsoft.AspNetCore.Mvc;

namespace ContosoPizza.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(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

The base class: ControllerBase

  • A controller is a public class with one or more public methods known as actions.

  • By convention, a controller is placed in the project root's Controllers directory.

  • The actions are exposed as HTTP endpoints via routing.

  • So an HTTP GET request to https://localhost:{PORT}/weatherforecast causes the Get() method of the WeatherForecastController class to be executed.

  • The first thing to notice is that this class inherits from the ControllerBase base class. This base class provides a lot of standard functionality for handling HTTP requests, so you can focus on the specific business logic for your application.

If you have experience with Razor Pages or model-view-controller (MVC) architecture development in ASP.NET Core, you've used the Controller class.

Don't create a web API controller by deriving from the Controller class. Controller derives from ControllerBase and adds support for views, so it's for handling webpages, not web API requests.

API controller class attributes

Two important attributes are applied to WeatherForecastController, as shown in the following code:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase

[ApiController] enables features that make it easier to build web APIs.

[Route] defines the routing pattern [controller]. The [controller] token is replaced by the controller's name (case-insensitive, without the Controller suffix).

This controller handles requests to https://localhost:{PORT}/weatherforecast.

The route might contain static strings, as in api/[controller]. If so, this controller would then handle a request to https://localhost:{PORT}/api/weatherforecast.

Try these

  1. What happens if you replace the route as given below

[Route("acme/[controller]")]
  1. What happens if you remove the [HttpGet(Name = "GetWeatherForecast")] attribute just above the action method?

Answer

The swagger will then throw an error, as the specification is not clear!

Even with this error, can you try calling the API directly from another tab in the browser like this:

https://localhost:7279/acme/WeatherForecast

Last updated