猿问

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

我正在使用 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?}");

            });

        }

    }

}

应用程序设置.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;"

    }

  }

}

如何修复它?


慕容森
浏览 195回答 2
2回答

慕森卡

正如评论中提到的,尝试将连接字符串移至顶部(建议)修复方法是将键 * *置于键"ConnectionStrings"之外logging应用程序设置.json{&nbsp; "ConnectionStrings": {&nbsp; &nbsp; &nbsp; "UserDatabase": "Server=DESKTOP-FSES7UK;Database=xxx;User Id=sa; Password=xxxxxxx;Trusted_Connection=True;"&nbsp; },&nbsp; "Logging": {&nbsp; &nbsp; "IncludeScopes": false,&nbsp; &nbsp; "LogLevel": {&nbsp; &nbsp; &nbsp; "Default": "Debug",&nbsp; &nbsp; &nbsp; "System": "Information",&nbsp; &nbsp; &nbsp; "Microsoft": "Information"&nbsp; }}

眼眸繁星

问题是你的ConnectionStrings对象已经是对象的属性Logging。写下你的appsettings.json如下:{&nbsp; "Logging": {&nbsp; &nbsp; "IncludeScopes": false,&nbsp; &nbsp; "LogLevel": {&nbsp; &nbsp; &nbsp; "Default": "Debug",&nbsp; &nbsp; &nbsp; "System": "Information",&nbsp; &nbsp; &nbsp; "Microsoft": "Information"&nbsp; &nbsp; },&nbsp; },&nbsp; "ConnectionStrings": {&nbsp; &nbsp; &nbsp; "UserDatabase": "Server=DESKTOP-FSES7UK;Database=xxx;User Id=sa; Password=xxxxxxx;Trusted_Connection=True;"&nbsp; }}
随时随地看视频慕课网APP
我要回答