Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ConnectionString from appsettings.json file?

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 ?

like image 493
JustProgrammer Avatar asked Dec 12 '25 03:12

JustProgrammer


2 Answers

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.

like image 69
Barbara Avatar answered Dec 14 '25 17:12

Barbara


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: enter image description here

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).

like image 44
Yiyi You Avatar answered Dec 14 '25 17:12

Yiyi You



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!