简体   繁体   English

ASP.NET Core 6启动时如何访问Configuration

[英]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 公开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;

WebApplication returned by WebApplicationBuilder.Build() also exposes Configuration and Environment : WebApplication WebApplicationBuilder.Build()返回的 WebApplication 还公开了ConfigurationEnvironment

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.

相关问题 我可以在ASP.NET Core启动期间访问数据库吗? - Can I access a database during startup in ASP.NET Core? 启动中的 ASP.NET 内核配置部分 - ASP.NET Core Configuration Section in Startup 如果自定义配置设置在ASP.NET Core 2应用程序启动过程中不存在/无效(托管在Windows服务中),如何正常失败? - How to fail gracefully if custom configuration settings are not present/valid during ASP.NET Core 2 application startup (hosted in a Windows Service)? 在启动期间验证 ASP.NET Core 选项 - Validation of ASP.NET Core options during startup 在 ASP.NET Core 启动期间使用 Serilog 和 Sentry - Using Serilog and Sentry during ASP.NET Core startup 在 ASP.Net Core 应用程序启动期间运行异步代码 - Run async code during startup in a ASP.Net Core application 在 ASP.NET Core MVC AddControllers 配置期间注册服务 - Register a service during ASP.NET Core MVC AddControllers configuration ASP.NET Core Web API,如何在启动类中访问 HttpContext - ASP.NET Core Web API, How can I access HttpContext in startup class 如何将 ASP.NET Core 3.1 中 Startup.cs 中的代码移动到 ASP.NET Core 6? - How to move code in Startup.cs in ASP.NET Core 3.1 to ASP.NET Core 6? 如何在启动期间通过调用 ASP.NET 内核中的外部 API 来在每个应用程序生命周期内初始化属性或变量一次? - How to initialize a property or variable once per application lifetime during startup by calling an external API in ASP.NET Core?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM