ASPNETCORE_ENVIRONMENT always Development when deploying to Azure

Author: mrhighstoneCreated Jun 9, 2026Updated Jul 25, 2026

For some reason the variable ASPNETCORE_ENVIRONMENT always defaults to Development. This results in a failing database initialization, as the ensureRecreated flag is true for IsDevelopment(). In Azure, EnsureDeletedAsync and EnsureCreatedAsync require access to the master database which is not granted by default.

if (ensureRecreated)
{
    await _context.Database.EnsureDeletedAsync();
    await _context.Database.EnsureCreatedAsync();
}
else
{
    await _context.Database.MigrateAsync();
}

I noticed the extension method WithAspNetCoreEnvironment sets this environment variable to Development when not set. But, where, how and at what moment should this variable be set to the corresponding environment?

public static IResourceBuilder<T> WithAspNetCoreEnvironment<T>(this IResourceBuilder<T> builder) 
    where T : IResourceWithEnvironment
{
    builder.WithEnvironment(context =>
    {
        var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
        context.EnvironmentVariables["ASPNETCORE_ENVIRONMENT"] = environment ?? "Development";
    });

    return builder;
}

Setting the Azure environment with the following statement results in the proper setting of the AZURE_ENV_NAME variable. Should the extension method WithAspNetCoreEnvironment use this variable instead?

azd env new staging
azd env select staging

Which would be resulting in the following extension method:

public static IResourceBuilder<T> WithAspNetCoreEnvironmentFromAzureEnvironment<T>(this IResourceBuilder<T> builder) 
    where T : IResourceWithEnvironment
{
    return builder.WithEnvironment(context =>
    {
        // Read from process environment variable instead of .NET configuration
        var envName = Environment.GetEnvironmentVariable("AZURE_ENV_NAME")
                      ?? "local";

        context.EnvironmentVariables["ASPNETCORE_ENVIRONMENT"] = envName.ToLowerInvariant() switch
        {
            "production" => "Production",
            "staging" => "Staging",
            _ => "Development"
        };
    });
}

Source: jasontaylordev/CleanArchitecture