With the release of .NET 6, when you create a new ASP.NET Core application, you no longer have a Startup.cs
file. Instead everything should be written inside the Program.cs
file:
var builder = WebApplication.CreateBuilder(args); | |
// Add services to the container. | |
builder.Services.AddRazorPages(); | |
var app = builder.Build(); | |
// Configure the HTTP request pipeline. | |
if (!app.Environment.IsDevelopment()) | |
{ | |
app.UseExceptionHandler("/Error"); | |
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. | |
app.UseHsts(); | |
} | |
app.UseHttpsRedirection(); | |
app.UseStaticFiles(); | |
app.UseRouting(); | |
app.UseAuthorization(); | |
app.MapRazorPages(); | |
app.Run(); |
If you don’t like this and you still want to use a Startup.cs
file, this is still possible.
First let’s recreate our good old Startup.cs
file:
public class Startup | |
{ | |
public Startup(IConfiguration configuration) | |
{ | |
Configuration = configuration; | |
} | |
public IConfiguration Configuration { get; } | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddRazorPages(); | |
} | |
public void Configure(WebApplication app, IWebHostEnvironment env) | |
{ | |
if (!app.Environment.IsDevelopment()) | |
{ | |
app.UseExceptionHandler("/Error"); | |
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. | |
app.UseHsts(); | |
} | |
app.UseHttpsRedirection(); | |
app.UseStaticFiles(); | |
app.UseRouting(); | |
app.UseAuthorization(); | |
app.MapRazorPages(); | |
app.Run(); | |
} | |
} |
In a first attempt, I tried the following:
var builder = WebApplication.CreateBuilder(args); | |
// This doesn't work. | |
builder.WebHost.UseStartup<Startup>(); | |
var app = builder.Build(); | |
app.Run(); |
Unfortunately, this didn’t work and resulted in the following error message:
Exception thrown: 'System.NotSupportedException' in Microsoft.AspNetCore.dll
An unhandled exception of type 'System.NotSupportedException' occurred in Microsoft.AspNetCore.dll
UseStartup() is not supported by WebApplicationBuilder.WebHost. Use the WebApplication returned by WebApplicationBuilder.Build() instead.
I switched to a more manual approach where I create the Startup class myself and invoke the methods directly:
var builder = WebApplication.CreateBuilder(args); | |
var startup = new Startup(builder.Configuration); | |
startup.ConfigureServices(builder.Services); | |
var app = builder.Build(); | |
startup.Configure(app, builder.Environment); |
Of course now it doesn’t matter anymore how the Startup.cs
file is structured or how you should name the different methods.