C#: Get ConnectionString From Appsettings.json Instead Of Being Hardcoded In .net Core 2.0 App

To get the ConnectionString from the appsettings.json file instead of hardcoding it in a .NET Core 2.0 App, you can follow these steps:

  1. Open the appsettings.json file and add the ConnectionString property under the "ConnectionStrings" section. For example:

    "ConnectionStrings": {
      "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
    
  2. In the Startup.cs file, add a private property to hold the IConfiguration instance:

    private IConfiguration _config;
    
  3. In the Startup.cs file, modify the ConfigureServices method to accept IConfiguration as a parameter and store it in the private property:

    public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
    {
        // Other configurations...
    
        _config = configuration;
    }
    
  4. In the Startup.cs file, modify the ConfigureServices method to retrieve the ConnectionString from the appsettings.json file:

    public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
    {
        // Other configurations...
    
        services.AddDbContext<YourDbContext>(options =>
            options.UseSqlServer(_config.GetConnectionString("DefaultConnection")));
    }
    
  5. In your class where you want to access the ConnectionString, inject IConfiguration:

    private readonly IConfiguration _config;
    
    public YourClass(IConfiguration config)
    {
        _config = config;
    }
    
  6. Now you can retrieve the ConnectionString value from the IConfiguration instance:

    string connectionString = _config.GetConnectionString("DefaultConnection");
    

Note: Make sure you have included the necessary NuGet packages such as Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Json in your project.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!