获取连接字符串时出错:ArgumentNullException:值不能为null。参数名称:connectionString

时间:2019-09-29 15:28:16

标签: c# asp.net-core entity-framework-core asp.net-core-2.1

我正在使用ASP.NET Core 2.0。下面是我的代码。

启动:

namespace foo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services
                .AddMvc()
                .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
            services.AddDbContext<fooContext>(options => options.UseSqlServer(Configuration.GetConnectionString("UserDatabase")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

appsettings.json:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    },
    "ConnectionStrings": {
      "UserDatabase": "Server=DESKTOP-FSES7UK;Database=xxx;User Id=sa; Password=xxxxxxx;Trusted_Connection=True;"
    }
  }
}

如何解决?

2 个答案:

答案 0 :(得分:0)

问题是您的ConnectionStrings对象是Logging对象的属性。如下编写您的appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    },
  },
  "ConnectionStrings": {
      "UserDatabase": "Server=DESKTOP-FSES7UK;Database=xxx;User Id=sa; Password=xxxxxxx;Trusted_Connection=True;"
  }
}

答案 1 :(得分:0)

如注释中所述,尝试将连接字符串移至顶部(建议),方法是使用* "ConnectionStrings" *键位于 logging 键之外< / p>

appsettings.json

{
  "ConnectionStrings": {
      "UserDatabase": "Server=DESKTOP-FSES7UK;Database=xxx;User Id=sa; Password=xxxxxxx;Trusted_Connection=True;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
  }
}