NET Core 6如何在启动过程中访问 Configuration

在早期版本中,我们使用 Startup.cs 类,并在 启动文件中获得如下配置对象。

public class Startup
{
private readonly IHostEnvironment environment;
private readonly IConfiguration config;


public Startup(IConfiguration configuration, IHostEnvironment environment)
{
this.config = configuration;
this.environment = environment;
}


public void ConfigureServices(IServiceCollection services)
{
// Add Services
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Add Middlewares
}


}

现在进去。NET 6(使用 VisualStudio2022)时,我们不会看到 Startup.cs类。看来它的日子不多了。因此,我们如何获得这些对象,如 Configuration (IConfiguration)和 HostEnvironment (IHostEnvironment)

我们如何获得这些对象,比如说从 apptings 读取配置。

using Festify.Database;
using Microsoft.EntityFrameworkCore;


var builder = WebApplication.CreateBuilder(args);


// Add services to the container.
builder.Services.AddRazorPages();


builder.Services.AddDbContext<FestifyContext>();




////////////////////////////////////////////////
// The following is Giving me error as Configuration
// object is not avaible, I dont know how to inject this here.
////////////////////////////////////////////////




builder.Services.AddDbContext<FestifyContext>(opt =>
opt.UseSqlServer(
Configuration.GetConnectionString("Festify")));




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();

我想知道如何从 appsetings.json 读取配置?

132009 次浏览

WebApplication.CreateBuilder(args)返回的 WebApplicationBuilder暴露了 ConfigurationEnvironment的属性:

var builder = WebApplication.CreateBuilder(args);


// Add services to the container.
...
ConfigurationManager configuration = builder.Configuration; // allows both to access and to set up the config
IWebHostEnvironment environment = builder.Environment;

WebApplicationBuilder.Build()返回的 WebApplication 也暴露了 ConfigurationEnvironment:

var app = builder.Build();
IConfiguration configuration = app.Configuration;
IWebHostEnvironment environment = app.Environment;

还要检查 迁徙指南代码示例

Program.cs中,WebApplicationBuilder 创建如下所示。

var builder = WebApplication.CreateBuilder(args);

一旦创建了生成器,就可以使用配置了。

让我们假设默认的 appSettings.json已经就位。下面的示例代码将从 JSON 配置文件中返回配置 Default 日志级别设置。

builder.Configuration["Logging:LogLevel:Default"] // returns "Warning"

一旦应用程序开始运行,你可以通过应用程序其他类的依赖注入访问配置设置。

public MyClass(IConfiguration configuration)
{
var logLevel = configuration["Logging:LogLevel:Default"];
}

值得考虑的一个很好的特性是创建一个表示设置的类,然后将配置绑定到该类类型的实例。例如,假设您创建了一个与 appSettings.json具有相同结构的名为 MyAppSettings的新类,您可以执行以下操作:

var myAppSettings = builder.Configuration.Get<MyAppSettings>();
string logLevel = myAppSettings.Logging.LogLevel.Default;

所有您需要的是添加“建造者。”在您的配置

比如:

builder.Services
.AddDbContext<FestifyContext>
(opt =>opt.UseSqlServer(builder.Configuration
.GetConnectionString("Festify")));


以下代码对我有效:

程序:

var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("conStr");
ConnectionString = connString;


...


partial class Program
{
public static string? ConnectionString { get; private set; }
}


calling class:
string cnStr = Program.ConnectionString;

这对我很管用

// Read in from JSON file
builder.Services.Configure<ConnectionKeys>(builder.Configuration.GetSection("ConnectionKeys"));

NET 6已经在 Program.cs 中提供了构建器对象

var builder = WebApplication.CreateBuilder(args);

只需使用这个构建器访问配置和 Environment,以从 app.setings.cs 获取 ConnectionString 为例,如下所示:

builder.Services.AddDbContext<DataContext>( options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnectiion"));
});

//. NET6 Program.cs-(获取应用程序配置属性)

var builder = WebApplication.CreateBuilder(args);


builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
builder.Configuration.AddJsonFile($"appsettings.Dev.json", optional: true);
builder.Configuration.AddEnvironmentVariables();


// projectwide instances
public IConfiguration _configuration;
public AccountsAPIController(IConfiguration configuration)
{
_configuration = configuration;
}


// _configuration.GetConnectionString("DefaultConnection");

这与之前的答案稍有不同,因为我在复习类似的东西,所以我把它包括在内。

Program.cs中,您还可以将代码分组在一个方法中,并调用该方法来减少运行次数,或者将类似的代码分组。我不会把所有的代码放进去; 我不会在这里放一个完整的 using指令列表,但是只要足够演示这种技术就行了,我会省略一些方法代码。这对于您的解决方案来说是不够的,甚至可能是太多了,需要您的自定义修饰。

using AutoMapper;
using MicroKnights.Log4NetHelper;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
...
//all your using directives
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;


//a variable to hold configuration
IConfiguration Configuration;


var builder = WebApplication.CreateBuilder(args);
Configuration = builder.Configuration;


// call some methods
ConfigureAuth(builder.Services);
ConfigureRedis(builder.Services);
ConfigureSession(builder.Services);
ConfigureMvc(builder.Services);
ConfigureServices(builder.Services);


var app = builder.Build();
ConfigureMiddleWare(app);
app.Run();
// we are done with the main part, now the methods


void ConfigureMvc(IServiceCollection services)
{
builder.Services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
config.Filters.Add(new AuthorizeFilter(policy));
})
.AddRazorPagesOptions(options => { options.Conventions.AddPageRoute("/Home/Login", ""); })
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
}


void ConfigureSession(IServiceCollection services)
{
builder.Services.AddSession(options =>
{
options.Cookie.Name = "mygreatsite_session";
options.IdleTimeout = TimeSpan.FromMinutes(60);
});
}


void ConfigureRedis(IServiceCollection services)
{
var redisConfig = new RedisOptions();
Configuration.GetSection(RedisOptions.RedisConfig).Bind(redisConfig);
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = redisConfig.ConnectionString;
options.InstanceName = "mygreatsite_";
});
services.AddDataProtection()
.SetApplicationName("MyGreatSite.Website")
.PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConfig.ConnectionString), "DataProtection-Keys");
}


void ConfigureMiddleWare(WebApplication app)
{
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}


app.UseRouting();
app.UseCors("default");
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();


app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute().RequireAuthorization();
endpoints.MapControllerRoute(
name: "Default",
pattern: "{controller=Home}/{action=Login}"
);
});
}

我知道这个问题最初要求 ASPNetCore,但是如果你碰巧想为一个工人服务做同样的事情,并且像我一样降落在这里,希望这个答案能够帮助你。

Worker Service 用户 IHostBuilder而不是 IWebApplicationBuilder,并且它不公开 Configuration 属性,但是您可以将 IHostBuilderContext 的实例接受到 ConfigureServices 方法中,该方法确实公开 Configuration 实例。

IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
var settings = context.Configuration.Get<Settings>();
})
.Build();

我用简单的方法解决了这个问题:

在 Program.cs 中:

using SomeAppName.Startup;


WebApplication.CreateBuilder(args)
.RegisterServices()
.Build()
.SetupMiddleware()
.Run();

下一步:

public static WebApplicationBuilder RegisterServices(this WebApplicationBuilder builder)
{
BuildConfiguration(builder.Environment);
//// Any code
}

最后:

private static IConfiguration BuildConfiguration(IHostEnvironment env)
{
var configurationBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("./Configuration/appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile("./Configuration/appsettings.other.json", optional: false, reloadOnChange: true)
.AddJsonFile($"./Configuration/appsettings.{env.EnvironmentName}.json", optional: true)
.AddJsonFile($"./Configuration/appsettings.other.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();


Configuration = configurationBuilder.Build();
return Configuration;
}