C# 获取连接字符串时出错:ArgumentNullException:值不能为null。参数名称:connectionString
我正在使用ASP.NETCore2.0。下面是我的代码 启动:C# 获取连接字符串时出错:ArgumentNullException:值不能为null。参数名称:connectionString,c#,asp.net-core,entity-framework-core,asp.net-core-2.1,C#,Asp.net Core,Entity Framework Core,Asp.net Core 2.1,我正在使用ASP.NETCore2.0。下面是我的代码 启动: namespace foo { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; }
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?}");
});
}
}
}
{
"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;"
}
}
}
如何修复它?问题是您的
连接字符串
对象已成为日志记录
对象的属性。编写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;"
}
}
如评论中所述,尝试将连接字符串移动到顶部(建议)修复方法是将键*
“ConnectionString”
*置于日志记录
键之外
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"
}
}
尝试在JSON文件的顶部使用ConnectionString。如果它能正常工作,那么您就是专业的。是的@Sajeetharan是对的。您在日志中有您的连接树。在那里找不到它。将连接字符串移到顶层日志之外谢谢,我多次发现错误类型。我会记住的。
尝试将连接字符串移到顶部
——这不是问题!您可以将它放在appsetings.json
中的任何位置。这不是实际的问题,但我建议将它放在的顶部或日志键的外部
——这意味着这也不是强制性的!!这是必须的。您不能将或与前面的句子放在一起!哈哈!谢谢你纠正它。我希望OP能得到答案:)所以没关系。@Sajeetharan欢迎!但在你多次修改你的答案之前,正确的答案已经发布了