[英]ASP.NET Core 6 how to access Configuration during startup
In earlier versions, we had Startup.cs class and we get configuration object as follows in the Startup file.在早期版本中,我们有 Startup.cs class,我们在Startup文件中得到配置 object,如下所示。
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
}
}
Now in .NET 6 (With Visual Studio 2022), we don't see the Startup.cs class. Looks like its days are numbered.现在在 .NET 6(使用 Visual Studio 2022)中,我们看不到Startup.cs class。看起来它的日子已经屈指可数了。 So how do we get these objects like Configuration(IConfiguration) and Hosting Environment(IHostEnvironment)
那么我们如何获得这些对象,如 Configuration(IConfiguration) 和 Hosting Environment(IHostEnvironment)
How do we get these objects, to say read the configuration from appsettings?我们如何获取这些对象,比如从 appsettings 中读取配置? Currently the Program.cs file looks like this.
当前 Program.cs 文件如下所示。
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();
I want to know how to read the configuration from appsettings.json?我想知道如何从 appsettings.json 读取配置?
WebApplicationBuilder
returned by WebApplication.CreateBuilder(args)
exposes Configuration
and Environment
properties: WebApplicationBuilder
WebApplication.CreateBuilder(args)
返回的 WebApplicationBuilder 公开Configuration
和Environment
属性:
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;
WebApplication
returned by WebApplicationBuilder.Build()
also exposes Configuration
and Environment
: WebApplication
WebApplicationBuilder.Build()
返回的 WebApplication 还公开了Configuration
和Environment
:
var app = builder.Build();
IConfiguration configuration = app.Configuration;
IWebHostEnvironment environment = app.Environment;
Also check the migration guide and code samples .还要检查迁移指南和代码示例。
In Program.cs
, the WebApplicationBuilder is created shown below.在
Program.cs
中,创建了如下所示的 WebApplicationBuilder。
var builder = WebApplication.CreateBuilder(args);
Once we have the builder created, the configuration is available.一旦我们创建了构建器,配置就可用了。
Let's assume you have the default appSettings.json
in place.假设您有默认的
appSettings.json
。 The example code below would return the configuration Default log level setting from the JSON configuration file.下面的示例代码将从 JSON 配置文件返回配置默认日志级别设置。
builder.Configuration["Logging:LogLevel:Default"] // returns "Warning"
Once the app is running, you can access the Configuration settings via dependency injection in other classes of your application.应用程序运行后,您可以通过应用程序的其他类中的依赖注入访问配置设置。
public MyClass(IConfiguration configuration)
{
var logLevel = configuration["Logging:LogLevel:Default"];
}
A nice feature worth considering it to create a class that represents your settings and then bind the configuration to an instance of that class type.一个值得考虑的好功能是创建一个代表您的设置的类,然后将配置绑定到该类类型的实例。 For example, let's assume you create a new class called
MyAppSettings
with the same structure as your appSettings.json
, you can do the following:例如,假设您创建了一个名为
MyAppSettings
的新类,其结构与您的appSettings.json
相同,您可以执行以下操作:
var myAppSettings = builder.Configuration.Get<MyAppSettings>();
string logLevel = myAppSettings.Logging.LogLevel.Default;
.NET 6 already gives builder object in Program.cs .NET 6 已经在 Program.cs 中提供了构建器对象
var builder = WebApplication.CreateBuilder(args);
Just use this builder to access configuration and Environment as an example to get ConnectionString from app.settings.cs as follows:只需使用此构建器访问配置和环境作为示例,即可从 app.settings.cs 中获取 ConnectionString,如下所示:
builder.Services.AddDbContext<DataContext>( options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnectiion"));
});
All you need is to add "builder."您只需要添加“构建器”即可。 before your Configuration
在您的配置之前
Like:喜欢:
builder.Services
.AddDbContext<FestifyContext>
(opt =>opt.UseSqlServer(builder.Configuration
.GetConnectionString("Festify")));
The following codes worked for me:以下代码对我有用:
Program.cs:程序.cs:
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;
This worked for me ---这对我有用---
// Read in from JSON file
builder.Services.Configure<ConnectionKeys>(builder.Configuration.GetSection("ConnectionKeys"));
This is slightly different than prior answers and I include this since I was reviewing something like this.这与之前的答案略有不同,我将其包括在内,因为我正在审查类似的内容。
In your Program.cs
you can also group code in a method and call that to keep it less run-on a bit or to group similar things.在您的
Program.cs
中,您还可以将代码分组到一个方法中并调用它以使其运行较少或对类似的事物进行分组。 I will not put all the code in;我不会把所有的代码都放进去; I will not put a full list of
using
directives here but just enough to demonstrate the technique and I will leave out some method code.我不会在此处列出
using
指令的完整列表,但足以演示该技术,并且我将省略一些方法代码。 This is not enough or even perhaps too much for your solution and will need your custom touchup.对于您的解决方案来说,这还不够,甚至可能太多,需要您的自定义修饰。
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}"
);
});
}
//.NET6 Program.cs -(to get the application configuration properties) //.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");
I know the question originally asks for ASPNetCore
but if you happen to looking to do the same for a worker service, and landed here like I did, hopefully, this answer helps you.我知道这个问题最初是针对
ASPNetCore
提出的,但是如果您碰巧希望为工作人员服务做同样的事情,并且像我一样来到这里,希望这个答案对您有所帮助。
Worker Service user IHostBuilder
instead of IWebApplicationBuilder
and that does not expose a Configuration property, but you can accept an instance of IHostBuilderContext into the ConfigureServices method, which does expose a Configuration instance. Worker Service 用户
IHostBuilder
而不是IWebApplicationBuilder
并且不公开 Configuration 属性,但您可以在 ConfigureServices 方法中接受 IHostBuilderContext 的实例,该方法确实公开了 Configuration 实例。
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
var settings = context.Configuration.Get<Settings>();
})
.Build();
I resolved this issue by simple way:我通过简单的方式解决了这个问题:
In Program.cs:在 Program.cs 中:
using SomeAppName.Startup;
WebApplication.CreateBuilder(args)
.RegisterServices()
.Build()
.SetupMiddleware()
.Run();
Next:下一个:
public static WebApplicationBuilder RegisterServices(this WebApplicationBuilder builder)
{
BuildConfiguration(builder.Environment);
//// Any code
}
Finally:最后:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.