I'm trying to created an ASP.NET Core 8 Web API using only CLI and have the program.cs as shown below.
When I run this from VS 2022, no compiler or runtime errors are appearing.
But when this is run from a "docker-compose up" I dot get specific error:
2024-03-28 17:54:11 Unhandled exception. System.InvalidOperationException: Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddAuthorization' in the application startup code.
2024-03-28 17:54:11 at Microsoft.AspNetCore.Builder.AuthorizationAppBuilderExtensions.VerifyServicesRegistered(IApplicationBuilder app)
2024-03-28 17:54:11 at Microsoft.AspNetCore.Builder.AuthorizationAppBuilderExtensions.UseAuthorization(IApplicationBuilder app)
2024-03-28 17:54:11 at WebApi.Program.Main(String[] args) in /app/Program.cs:line 41
Code:
using Microsoft.EntityFrameworkCore;
namespace WebApi
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
services.AddControllers();
/*
Console.WriteLine("Preparing DbContext");
services.AddDbContext<ParkingDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
*/
services.AddAuthorization(); // Move AddAuthorization here
services.AddHealthChecks();
var app = builder.Build();
app.UseAuthorization();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI();
}
// Configure the HTTP request pipeline.
app.UseRouting();
app.MapControllers();
app.Run();
}
}
}
As you notice I do have the .AddAuthorization method above but when run and opening a browser localhost is not running.
I'm probably missing something very obvious here, have spent some hours searching here without any luck.
According to your shared code snippet, you are having the right exception. Though, you have added the
app.UseAuthorization()however, the middleware order has not been followed. Consequently, it has thrown that error.In order to inject middleware order correctly,
app.UseAuthorization()should be called afterapp.UseRouting()in middleware pipeline. This is essential for the authorization middleware to process requests after routes have been matched.Correct order would be:
Note: Above order should resolve your error. In addition, please refer to this official document.