值不能为空。参数名称:starter 中的 connectionString appsettings.json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40874640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:43:50  来源:igfitidea点击:

Value cannot be null. Parameter name: connectionString appsettings.json in starter

jsonasp.net-coreasp.net-core-1.0appsettings

提问by epv

I am trying to write my connection string in my appsettings.json file and bring it into my startup file but I keep getting a Value cannot be null. Parameter name: connectionString. I have been using various examples but can't seem to see this new setup with ASP.NET 1.0 Core startup class.

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

Appsetting.json file:

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"
  }
}
}
}

Method attempting Startup.cs

尝试 Startup.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
}

回答by GlennSills

First of all, the

首先,该

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

Is slightly different from the structure you get when you add a "Asp.NET Configuration File" in Visual Studio. When you do that you get

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

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

without the "Data" JavaScript Object. So that's why the extension method isn't working. It expects this structure. You can use this structure (the one with "Data") anyway and get your connection string like so:

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

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

Notice that you are navigating through the JavaScript object tree using :instead of .. That's due to some cross-platform issues with using the ..

请注意,您正在使用:代替浏览 JavaScript 对象树.。这是由于使用..

If you edit out the "Data":{} you can do this :

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

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

Now the extension method will work. Underneath the Microsoft extensions it is the same thing as the code above.

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

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

回答by StefanJM

I was missing the letter 's' after the ConnectionStringproperty name in the appsettings.json when using Configuration.GetConnectionString("name")

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

enter image description here

在此处输入图片说明

If you want to copy

如果你想复制

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

The method wording GetConnectionStringconfused me, I hovered over it and oh be hold it was looking for ConnectionStringsproperty name instead of ConnectionString

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

回答by Rudis

DefaultConnectionis the inner object in the json structure and it is the child of Dataobject.

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

So if you want to be exact with your config file you can use

因此,如果您想准确使用配置文件,可以使用

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

回答by noelicus

I got this because I had a connection string with a \in it, which needed escaping to be a \\. So my localdb connection string was causing a load error like this:

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

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

and was fixed by making it:

并通过制作它来修复:

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

回答by Ashwinee Vaishampayan

I had got similar error.My "appsettings.json" file was not loading because the properties of the file was Copy to Output Directory -> Do not Copy. I set that to Copy always save and rebuild.It worked.

我遇到了类似的错误。我的“appsettings.json”文件没有加载,因为文件的属性是复制到输出目录 -> 不复制。我将它设置为复制总是保存和重建。它起作用了。

回答by Slothario

I fought with the null connection string issue far too long, only to find I was doing this:

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

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

I was using both the ConnectionStrings:prefix AND GetConnectionString. When I removed the prefix it worked:

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

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

回答by CYCLONE

I experienced this problem using asp.net core 3.0. The workaround fix for me is:

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

Instead of:

代替:

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

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

Use this:

用这个:

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

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

The emphasis here is the double colon in the connection configuration.

这里的重点是连接配置中的双冒号。

回答by Douglas Loaiza

this is was the message that appeared me

这是出现在我面前的消息

Value cannot be null. Parameter name: connectionString

值不能为空。参数名称:connectionString

I fix it changed in the startup these lines

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

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

To

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

回答by tohid badri

in asp.net core you must add IConfiguration to startUp contractor method and assignee this Parameter to a property inherited from IConfiguration inside class

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

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

回答by Satya Arya

Another mistake in my case was that I was using ConnectionString, instead ConnectionStrings (Note last 's')

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