Writing Controllers in ASP.NET Core

Blog header image

(The current state of the application code can be found on GitHub. You can verify your code if you've been following along, or if you're just joining in, you can get the current state of the code and follow along from here.)

Before we can actually write a controller, we need to add controller support into our application. Clone my starter project from GitHub, open Startup.cs, and then add the following code to the ConfigureServices() method after the AddCors() call:

public void ConfigureServices(IServiceCollection services)
{
services.AddCors(...);

services.AddControllers();
}

services.AddControllers() registers several parts of the ASP.NET Core platform as services.

Next, add the following code to the Configure() method after the UseCors() call:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Other code
app.UseCors();

app.UseRouting();

app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}