the question is how to get the ConnectionString from appsetting.json file in ASP NET Core 3.1 application? Here is the appsetings.json file
"ConnectionStrings": {
"DefaultConnection": "data source=exmaple;initial catalog=example;persist security info=True;user id=example;password=example"
}
In the example, all parameters are hidden behind the names example
In the Program.cs class, I include files
static void ConfigureAppConfiguration(WebHostBuilderContext context, IConfigurationBuilder config, string[] args)
{
config
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName.ToLowerInvariant()}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args);
}
and when I try to get the connection string values in the Startup class, I get null
public void ConfigureServices(IServiceCollection services)
{
var connetctionString = config.GetConnectionString("DefaultConnection");
...
}
Why connection == null ?
In addition to the previous answer, you could also use in the Startup.cs the method you did, so it would look in the following:
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("DefaultConnection");
}
Also be aware that you do not need to specify the configuration files explicitly in the Program.cs. You also could use the Host.CreateDefaultBuilder-method, which automatically adds the files.
Here is a demo:
startup:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var connetctionString = Configuration.GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;
appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "data source=exmaple;initial catalog=example;persist security info=True;user id=example;password=example"
}
}
result:

Update:
Program.cs:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName.ToLowerInvariant()}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
And if you want to set configuration in program.cs,you can refer to the official doc,and set it in public static IHostBuilder CreateHostBuilder(string[] args).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With