在ASP.NET Core 3.1中使用配置中的ConnectionString

问题描述 投票:0回答:1

我正在使用推荐的方法用ASP.NET Core配置Serilog。

如何从Main方法中的配置中获取ConnectionString来配置SQL Server sink?

public class Program {
  public static Int32 Main(String[] args) {

    Log.Logger = new LoggerConfiguration()
      .MinimumLevel.Debug()
      .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
      .Enrich.FromLogContext()
      .WriteTo.Console()
      .CreateLogger();

    try {
      CreateHostBuilder(args).Build().Run();
      return 0;
    } catch (Exception exception) {
      return 1;
    } finally {
      Log.CloseAndFlush();
    }

  }

  public static IHostBuilder CreateHostBuilder(String[] args) {

    IHostBuilder builder = Host.CreateDefaultBuilder(args);

    builder
      .UseSerilog()
      .ConfigureWebHostDefaults(builder => {

      builder
        .ConfigureAppConfiguration((context, configuration) => {

          IWebHostEnvironment environment = context.HostingEnvironment;

          configuration
            .AddJsonFile("settings.json", false, true)
            .AddJsonFile($"settings.{environment.EnvironmentName}.json", false, true)
            .AddEnvironmentVariables();

        }) 
        .UseStartup<Startup>();

    });

    return builder;      
  } 
} 

我使用的是:- Serilog: 2.9.0- Serilog.Sinks.MSSqlServer: 5.3.0

在:.NET Core 3.1

asp.net-core serilog asp.net-core-3.1
1个回答
1
投票

你可以得到环境。

var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

然后用它来手动配置一个构建器,就像你下面做的那样。

var configuration = new ConfigurationBuilder()
    .AddJsonFile("settings.json", false, true)
    .AddJsonFile($"settings.{environment}.json", false, true)
    .AddEnvironmentVariables()
    .Build();

然后像平常一样获取连接字符串

var connectionString = configuration.GetConnectionString("...")
© www.soinside.com 2019 - 2024. All rights reserved.