从 .NET 6 中的构建器设置中访问当前环境(开发、生产等)

geo*_*ode 4 c# authorization environment-variables .net-core .net-6.0

我正在 .NET 6 中构建一个使用身份验证和基于策略的授权的应用程序。两者功能都很好。但是,我需要创建一种在开发环境中绕过授权的方法。下面是我在program.cs中的代码。

我创建了一个禁用授权的类,并将其添加到构建器中。builder.Services.AddSingleton<IAuthorizationHandler, DisableAuthorization>(); 这工作正常,我现在需要做的就是使其以环境“开发”为条件。我的问题是我不知道如何从构建器中获取当前环境(我确实知道构建后如何执行 - 例如,app.Environment.IsDevelopment())。

我已经在网上搜索过,但我能找到的所有解决方案都涉及注入 Startup() 和 ConfigureServices() 方法 - 这两个方法都已被 WebApplication.CreateBuilder取代取代。

在构建应用程序之前获取环境的最有效方法是什么?

当前代码(Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();
builder.Services.AddServerSideBlazor();
builder.Services.AddHttpClient();
builder.Services.AddSingleton<IAppState, AppState>();
builder.Services.AddScoped<IAuthorizationHandler, IsAdminHandler>();
...


//Add authentication and register CAS as the authentication handler
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

    // Add cookie authentication
    ...

builder.Services.AddAuthorization(options =>
    {
        // Add access policies
        options.AddPolicy("IsAdmin", Policies.IsAdminPolicy());
        options.AddPolicy("IsManager", Policies.IsManagerPolicy());
        options.AddPolicy("IsUser", Policies.IsUserPolicy());
        options.AddPolicy("IsReadOnly", Policies.IsReadOnlyPolicy());

        // Add fallback authorization which blocks unauthenticated access to all pages
        // unless the [AllowAnonymous] attribute is applied to the route in the controller
        options.FallbackPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
    }
);

// Disable authorization in DEV
builder.Services.AddSingleton<IAuthorizationHandler, DisableAuthorization>();

// Run the builder and return the configured application to "app" 
var app = builder.Build();


// Configure the HTTP request pipeline by adding middleware
if (app.Environment.IsDevelopment())
{
    // Use detailed exception page (for development environment only)
    app.UseDeveloperExceptionPage();

    // Require HTTPS connection.  The default HSTS value is 30 days. 
    app.UseHsts();
}
else if (app.Environment.IsProduction())
{

    // Enable standard error page
    app.UseExceptionHandler("/Error");

    // Require HTTPS connection. The default HSTS value is 30 days. 
    // You may want to change this for production scenarios, 
    // see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
else
{
    throw new GenericException("Environment has not been set or is incorrect");
}
Run Code Online (Sandbox Code Playgroud)

Gur*_*ron 8

您可以Environment在以下位置使用属性WebApplicationBuilder

var isDev = builder.Environment.IsDevelopment();
Run Code Online (Sandbox Code Playgroud)