【问题标题】:Value cannot be null. Parameter name: connectionString appsettings.json in starter值不能为空。参数名称:starter中的connectionString appsettings.json
【发布时间】:2017-04-13 23:11:12
【问题描述】:

我正在尝试在我的 appsettings.json 文件中写入我的连接字符串并将其带入我的启动文件,但我不断得到一个值不能为空。 参数名称:连接字符串。我一直在使用各种示例,但似乎无法通过 ASP.NET 1.0 Core 启动类看到这个新设置。

Appsetting.json 文件:

{
"Data": {
"DefaultConnection": {
  "ConnectionString": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"

},
"Logging": {
  "IncludeScopes": false,
  "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
  }
}
}
}

方法尝试 启动.cs

public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

 public void ConfigureServices(IServiceCollection services)
    {
        var connStr = Configuration.GetConnectionString("DefaultConnection");
        System.Console.WriteLine(connStr);
        services.AddDbContext<DbContext>(options => options.UseSqlServer(connStr)); //error right here -- Null value
}

【问题讨论】:

    标签: json asp.net-core asp.net-core-1.0 appsettings


    【解决方案1】:

    您需要将您的appsetting.json更改为:

        {
      "Data": {
        "ConnectionStrings": {
          "DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"
    
        },
        "Logging": {
          "IncludeScopes": false,
          "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
          }
        }
      }
    }
    

    现在可以工作了:

      var connStr = Configuration.GetConnectionString("DefaultConnection");
    

    【讨论】:

    • ConnectionString 不能是 Data 的子级,因为 GetConnectionString('DefaultConnection) 是 Configuration["ConnectionString:DefaultConnection"] 的简写
    【解决方案2】:

    DefaultConnection是json结构中的内部对象,是Data对象的子对象。

    所以如果你想准确地使用你的配置文件,你可以使用

    var connStr = Configuration.GetSection("Data")
                               .GetSection("DefaultConnection")["ConnectionString"];
    

    【讨论】:

    • GetSection 的东西不是必需的。您可以使用“:”作为分隔符导航对象树。因此 Configuration["Data:DefaultConnection:ConnectionString"] 是等效的。请参阅下面的答案。
    【解决方案3】:

    首先,

     "Data": {
    "ConnectionStrings": {
      "DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"},
    }
    

    与在 Visual Studio 中添加“Asp.NET 配置文件”时获得的结构略有不同。当你这样做时,你会得到

    "ConnectionStrings": {
      "DefaultConnection": "Data Source=server;Initial Catalog=dbase;Trusted_Connection=True;MultipleActiveResultSets=true"},
    

    没有“数据”JavaScript 对象。所以这就是扩展方法不起作用的原因。它期望这种结构。无论如何,您都可以使用这种结构(带有“数据”的结构)并获得连接字符串,如下所示:

    var connectionString = Configuration["Data:ConnectionStrings:DefaultConnection"];
    

    请注意,您正在使用 : 而不是 . 在 JavaScript 对象树中导航。这是由于使用. 时出现的一些跨平台问题。

    如果您编辑掉“数据”:{},您可以这样做:

    var connectionString = Configuration["ConnectionStrings:DefaultConnection"];
    

    现在扩展方法将起作用。在 Microsoft 扩展下,它与上面的代码相同。

    var config2 = Configuration.GetConnectionString("DefaultConnection");
    

    【讨论】:

    • 您一直提到“App”,但在 Json 中,如果没有“App”,也许您的意思是“Data”?我很困惑。
    • 你是对的@mastazi,很好!几年来,人们一直在让这种情况发生。我已经编辑了帖子。
    • 感谢@GlennSills 澄清这一点!
    • var connectionString = Configuration["Data::ConnectionStrings:DefaultConnection"]; 中有错字。双冒号:: 应替换为单冒号:
    • 谢谢!你刚刚救了我的命。我花了 2 个小时想知道为什么我的用户机密连接字符串没有被拾取。事实证明,您需要使用这种确切的语法才能使其工作:dotnet user-secrets set ConnectionStrings:&lt;your connection string name&gt; "value"
    【解决方案4】:

    这是出现在我身上的消息

    值不能为空。 参数名称:连接字符串

    我修复它在启动时更改了这些行

    services.AddDbContext<AppIdentityDbContext>(options =>
    options.UseSqlServer(
    Configuration["Data:BookStoreContext:ConnectionString"]));
    

    services.AddDbContext<AppIdentityDbContext>(options =>
    options.UseSqlServer(
    Configuration.GetConnectionString("BookStoreContext")));
    

    【讨论】:

      【解决方案5】:

      我遇到了类似的错误。我的“appsettings.json”文件没有加载,因为文件的属性是复制到输出目录 -> 不要复制。我将其设置为 Copy always save and rebuild.It 工作。

      【讨论】:

        【解决方案6】:

        在使用 Configuration.GetConnectionString("name") 时,我在 appsettings.json 中的 ConnectionString 属性名称后面缺少字母“s”

        如果你想复制

        "ConnectionStrings ": {
          "SpyStore": "Server=(localdb)\\mssqllocaldb;Database=SpyStore;Trusted_Connection=True;MultipleActiveResultSets=true;"
        }
        

        GetConnectionString 的方法措辞让我很困惑,我将鼠标悬停在它上面,哦,请记住它正在寻找 ConnectionStrings 属性名称而不是 ConnectionString

        【讨论】:

        • 只需花半小时尝试不同类型的连接字符串,这是我的问题....谢谢您的回答
        • 大声笑,真不敢相信我花了很长时间试图找出我做错了什么,最后它丢失了一封信,谢谢 Stefan 发帖:)
        【解决方案7】:

        我与空连接字符串问题斗争了太久,才发现我正在这样做:

        builder.Services.AddDbContext<MlDataContext>(provider => new MlDataContext(config.GetConnectionString("ConnectionStrings:SqlConnectionString")));
        

        我同时使用了ConnectionStrings: 前缀和GetConnectionString。当我删除前缀时它起作用了:

        builder.Services.AddDbContext<MlDataContext>(options => options.UseSqlServer(config.GetConnectionString("SqlConnectionString")));
        

        【讨论】:

          【解决方案8】:

          我在使用 asp.net core 3.0 时遇到了这个问题。 我的解决方法是:

          代替:

          var 连接字符串 = 配置["ConnectionStrings:DefaultConnection"];

          使用这个:

          var 连接字符串 = 配置["ConnectionStrings::DefaultConnection"];

          这里强调的是连接配置中的双冒号。

          【讨论】:

          • 为什么是双冒号?有什么区别?
          • 在找到这个答案之前,我仍然面临同样的问题。谢谢
          【解决方案9】:

          我得到这个是因为我有一个带有\ 的连接字符串,它需要转义为\\。所以我的 localdb 连接字符串导致了这样的加载错误:

          "DefaultConnection": "Server=(localdb)\myinstance;Integrated Security=true;Initial Catlog=my-localdb;"
          

          并通过修复:

          "DefaultConnection": "Server=(localdb)\\myinstance;Integrated Security=true;Initial Catlog=my-localdb;"
          

          【讨论】:

            【解决方案10】:

            在 asp.net 核心中,您必须将 IConfiguration 添加到 startUp 承包商方法,并将此参数分配给从类内部 IConfiguration 继承的属性

             public class Startup
            {
                public Startup(IConfiguration configuration)
                {
                    this.Configuration = configuration;
                }
                public IConfiguration Configuration { get; }
            

            【讨论】:

            • 请编辑您的答案以将建议的代码包含为文本(格式化为代码块)。以图片形式发布的代码没有用处。
            【解决方案11】:

            我的另一个错误是我使用的是 ConnectionString,而不是 ConnectionStrings(注意最后一个 's')

            【讨论】:

              【解决方案12】:

              也许你可以试试这个:

              services.AddDbContext<ApplicationDbContext>(options =>
                  options.UseSqlServer("DefaultConnection")
              );
              

              然后设置你的appsettings.json 做这样的事情:

              "ConnectionStrings:": {
                  "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=HOME1_DATABASE;Trusted_Connection=True;MultipleActiveResultSets=true"
              },
              

              之后,当我通过控制台添加迁移时,它成功了。

              【讨论】:

                【解决方案13】:

                使用 Postgres SQL 时,appsettings.Development.json 必须包含

                "ConnectionStrings": {  
                      "DefaultConnection": "User ID=user;Password=xxxx;Host=127.0.0.1;Port=5432;Database=abc;Pooling=true"
                    }  
                

                Startup.cs 文件中的内容类似于

                 public void ConfigureServices(IServiceCollection services)
                    {
                        services.AddDbContext<ApplicationDbContext>
                        (p => p.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));            
                    }
                

                【讨论】:

                  【解决方案14】:

                  对于 Postgre Db,下面对我有用

                      private readonly IConfiguration _config;
                  
                      string connectionString;
                      public DataBaseContext(IConfiguration config)
                      {
                          _config = config;
                          connectionString= _config.GetValue<string>("ConnectionStrings:sampleConnection");
                      }
                  

                  配置文件:

                  “连接字符串”:{ “样品连接”:“..” }

                  启动文件: services.AddScoped();

                  【讨论】:

                    【解决方案15】:

                    我的问题是通过修正一个错字来解决的

                    【讨论】:

                      【解决方案16】:

                      就我而言,我的 Startup 类中有两个 IConfiguration 定义。没有帮助:)

                      【讨论】:

                        【解决方案17】:

                        我在使用 Asp.Net Core 5 的那天遇到了这个错误。我尝试了上述所有解决方案,但都不满意。然后我删除了 appsettings.json 文件的“ConnectionStrings”部分并启动了迁移。错误发生后,我重写了该部分并再次启动了迁移。一切正常。

                        【讨论】:

                          【解决方案18】:

                          请确保您在 app.json 中定义了所有连接字符串。 我的问题是我有两个不同的项目在他们的服务配置中添加了一个 dbContext

                          1. 引用了identityDb的身份项目
                          2. 我所有的数据访问逻辑的持久化项目

                          我通过在 app.json 中定义两个连接字符串解决了这个问题

                          【讨论】:

                            【解决方案19】:

                            将连接字符串添加到appsetting.json 文件的正确方法如下:

                            "ConnectionStrings":{
                               "DefaultConnection":"Server=localdb)\\MSSQLLocalDB;Datbase=MyShop;Trusted_Connection=true"
                            }
                            

                            【讨论】:

                              【解决方案20】:
                              • 我明白了,是因为应用设置中的连接字符串名称与启动中的配置不同!!!

                              • 启动时连接字符串配置的正确代码

                              // replace NAMEHERE with the name of the class that inherits from DbContext
                              services.AddDbContextPool <NAMEHERE> (opts => opts.UseSqlServer(Configuration.GetConnectionString("here put the same Connection string name that in appsettings")));
                              

                              【讨论】:

                                猜你喜欢
                                • 1970-01-01
                                • 2021-10-11
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 2016-01-16
                                相关资源
                                最近更新 更多