0

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

1 Answer 1

2

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);
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.