Rahul Dev
Rahul Dev

Reputation: 141

how to read connection string using configuration in .NET CORE 3.1

I'm migrating my code from .NET CORE 2.2 to .NET CORE 3.1. I'm encountering the below error while reading connection string from appsettings.json

"'Configuration' does not contain a definition for 'GetConnectionString'"

I'm using the below code in startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
    services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

My appsettings.json is as below

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },

  "ConnectionStrings": {
    "DefaultConnection": "Data Source=abc.net;Initial Catalog=xyz;User ID=paper;Password=pencil"
  },
  "AllowedHosts": "*",

  "serverSigningPassword": "key",
  "accessTokenDurationInMinutes": 2
}

Is there any way to read this connection string and other variables in appsettings.json

Upvotes: 0

Views: 2049

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222722

There are few things to be noted,

Have you injected in the constructor?

public Startup(IConfiguration configuration)
{
  Configuration = configuration;
}

public IConfiguration Configuration { get; }

and use it as

 public void ConfigureServices(IServiceCollection services)
  {
     var connection = Configuration.GetConnectionString("DefaultConnection");
     services.AddDbContext<ShelterPZ_DBContext>(options => options.UseSqlServer(connection));
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
  }

Upvotes: 2

Related Questions