简体   繁体   中英

Adding a custom provider to Asp.Net Core

I have the following code in my Program.cs:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)            
        .ConfigureAppConfiguration(b => b
            .AddEnvironmentVariables()
            .AddMyCustomConfiguration(o => o.UseSqlServer(
                Environment.GetEnvironmentVariable("ConnectionStrings:MyDatabase"))))                
        .UseStartup<Startup>();

My appsettings.json looks like this:

{
  "ConnectionStrings": {
    "MyDatabase": "connectionstring"
  }
}

However, Environment.GetEnvironmentVariable("ConnectionStrings:MyDatabase") is returning null. I was under the impression that AddEnvironmentVariables would load the necassary variables. Is this not the case / how can I get this to load the connection string?

See this example

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
  .ConfigureAppConfiguration((hostingContext, config) =>
  {
    var env = hostingContext.HostingEnvironment;

    config.AddJsonFile("application.json", optional: false, reloadOnChange: true);
    config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
    config.AddEnvironmentVariables("ASPNETCORE_");
    config.AddCommandLine(args);
  })
  .UseStartup<Startup>();

here you have the link to the article https://www.johanohlin.com/blog/configuration-providers-in-aspnet-core/

You've put your settings into JSON config, not into env var(s). This is why GetEnvironmentVariable() returns nothing. And ASP.Net Core is not intended to export your config to env vars unless you did that explicitly (let say, via SetEnvironmentVariable() or an equivalent).

If you actually intend to just read a connection string value, take a look on this topc How to read connection string in .NET Core?

For getting ConnectionStrings from appsettings.json , you should use GetConnectionString instead of reading environment.

Try something like below:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)            
    .ConfigureAppConfiguration(b => {
            b.AddEnvironmentVariables();
            var connectionString = b.Build().GetConnectionString("MyDatabase");
            .AddMyCustomConfiguration(o => o.UseSqlServer(connectionString));
    })              
    .UseStartup<Startup>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM