как читать строку подключения с помощью конфигурации в .NET CORE 3.1

Я переношу свой код с .NET CORE 2.2 на .NET CORE 3.1. Я сталкиваюсь с приведенной ниже ошибкой при чтении строки подключения из appsettings.json.

"" Конфигурация "не содержит определения для" GetConnectionString ""

Я использую приведенный ниже код в startup.cs

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

Мой appsettings.json выглядит следующим образом

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

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

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

Есть ли способ прочитать эту строку подключения и другие переменные в appsettings.json


person Rahul Dev    schedule 17.04.2020    source источник


Ответы (1)


Следует отметить несколько моментов.

Вы ввели конструктор?

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

public IConfiguration Configuration { get; }

и использовать его как

 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);
  }
person Sajeetharan    schedule 17.04.2020