API Controllers in .NET 5 needs to be implemented slightly differently than .NET Framework controllers. I’ll go over some of the few differences when creating a .NET 5 controller.

Base controllers

In .NET 5, there are two different ways of creating a controller. Creating an MVC controller is slightly different than creating an API controller.

Let’s start off by creating the .NET 5 solution using the .NET Core CLI.

dotnet new sln -n WebApiExamples
dotnet new webapi -n WebApiStartup
dotnet sln .\WebApiExamples.sln add .\WebApiStartup\WebApiStartup.csproj

The first two lines created the solution and project file, respectively. The final line attaches the project into the solution file.

Executing the above three lines will scaffold a solution file and a web api project with basic example controller class in there. Using dotnet run on the project directory should allow the web api example to run and the endpoints can then be accessed.

API Controller

namespace WebApiStartup.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();
        }
    }
}

The first thing that I can see when looking at the controller is that the WeatherForecastController inherits the ControllerBase class. This is intended as the Controller class should only be inherited from MVC type controllers.

With API controllers, it is also recommended to use attribute routing as this would allow Swashbuckle to automatically create the Open API specifications.

In fact, to get swashbuckle up and running, all we need to do is add the following commands in the startup class:

app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApiStartup v1"));

With API controllers, we need to add the [ApiController] attribute which is used to let .NET know this is an API controller.

Logging in .NET 5

In the controller example above, we can see an ILogger<> argument passed into the constructor. The ILogger<> generic class accepts a class which will be used as a log category. It will use a string representation of the class to be used as a category. We can create custom categories but for the most part, passing in the class name should be sufficient. In the Startup.cs class however, we need to ensure that we add a few log providers. The log providers will allow us to log into a file or wherever we want to log information.

Sample repository

A sample repository of the working example can be found at Web API Example