【问题标题】:How to read a ConnectionString from appsettings.json in a Razor Pages Project如何从 Razor Pages 项目中的 appsettings.json 读取 ConnectionString
【发布时间】:2021-12-13 23:23:08
【问题描述】:

我的appsettings.json 看起来像:

  "ConnectionStrings": {
      "TestDB": {
          "ConnectionString": "Server=TheServer;Database=MyDatabase;Trusted_Connection=True;",
          "ProviderName": "System.Data.SqlClient"
}

我正在尝试使用以下方式访问连接字符串:

ConfigurationManager.ConnectionStrings[dbName].ConnectionString;

这会引发 Null Exception 错误,我不确定原因。

【问题讨论】:

  • this 有帮助吗?
  • @GuruStron 我遇到了一个错误; CS1061“IServiceCollection”不包含“AddDbContext”的定义,并且找不到接受“IServiceCollection”类型的第一个参数的可访问扩展方法“AddDbContext”
  • @OliverGuy 这是完全不同的错误。您似乎忘记添加实体框架 NuGet 包或只是 using Microsoft.Extensions.DependencyInjection;
  • @Agrgg 我添加了using Microsoft.Extensions.DependencyInjection;
  • @OliverGuy 然后确保您已添加 Microsoft.EntityFrameworkCore Nuget 包。

标签: c# connection-string razor-pages appsettings configurationmanager


【解决方案1】:

ConfigurationManager已过时,需要在.NET Сore环境中使用IConfigurationIConfiguration由.NET Core内置依赖注入提供)。

例如,请参阅this answer

【讨论】:

    【解决方案2】:

    扩展用户@Agrgg 所说的内容: https://stackoverflow.com/a/66658317/3712531

    ConfigurationManager 已过时,需要在.NET Сore 环境中使用IConfiguration(IConfiguration 由.NET Core 内置依赖注入提供)。

        private readonly IConfiguration config;
    
        public MyConstructor(IConfiguration config)
        {
            this.config = config;
        }
        public void DoSomethingFunction()
        {
            string settings1 = config["Setting1"];
        }
    

    【讨论】:

      猜你喜欢
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-29
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多