簡體   English   中英

Asp.Net Core 2.0 ArgumentNullException:值不能為null。 參數名稱:connectionString

[英]Asp.Net Core 2.0 ArgumentNullException: Value cannot be null. Parameter name: connectionString

我在PC上使用ASP.NET Core 2.0,Visual Studio 2017 Enterprise,版本15.5.4和本地數據庫。

我是第一次使用數據庫,並且遇到了以下問題:

處理請求時發生未處理的異常。
ArgumentNullException:值不能為null。
參數名稱:connectionString。

閱讀並嘗試所有可能的建議以及可能的解決方案后,問題仍然存在。

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

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {    
        services.AddMvc();
        services.AddDbContext<VideosContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }

    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?}");
        });
    }
}
    {
      "ConnectionString": {
        "DefaultConnection": "Server =(localdb)\\mssqllocaldb;Database=Videos;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
    "Logging": {
      "IncludeScopes": false,
      "LogLevel": {
        "Default": "Warning"
      }
    }
}

public static void Main(string[] args)
{
     BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
   WebHost.CreateDefaultBuilder(args)
      .UseStartup<Startup>()
      .Build(); 

我究竟做錯了什么? 預先感謝您的任何建議。

您的應用設置JSON文件的語法是否正確?

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

您正在使用GetConnectionString方法從appsettings.json獲取連接字符串的值,因此您需要考慮到該方法只是GetSection("ConnectionStrings")["name"]的簡寫。

由於您的appsettings.json中有ConnectionString (單數),因此會出現此類錯誤(即,沒有ConnectionString鍵)。

如果要保留單鍵,則應改用GetSection("ConnectionString")["DefaultConnection"] 否則,您需要更新appsettings.json文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM