提问人:apteta 提问时间:9/16/2023 最后编辑:marc_sapteta 更新时间:9/16/2023 访问量:83
ASP.NET Core 6.0:值不能为空。参数名称:starter中的connectionString appsettings.json
ASP.NET Core 6.0 : Value cannot be null. Parameter name: connectionString appsettings.json in starter
问:
我正在尝试从我的文件中获取我的连接字符串并在我的启动文件中使用它,但我不断收到错误appsettings.json
值不能为 null。参数名称:connectionString。
这是我的文件:Appsetting.json
{
"Project": {
"ConnectionStrings": "Data Source=(local)\\SQLSERVER; Database=RecommendationSite; Persist Security Info=false; User ID='sa'; Password='sa'; MultipleActiveResultSets=True; Trusted_Connection=False;",
"CompanyName": "RecommendationSite1 ",
"CompanyPhone": "+7 (111) 111-11-11",
"CompanyPhoneShort": "+71111111111",
"CompanyEmail": "[email protected]"
}
}
尝试读取该连接字符串的方法:Startup.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using RecommendationSite.Data;
using RecommendationSite.Domain.Repositories.Abstract;
using RecommendationSite.Domain.Repositories.EntityFramework;
using RecommendationSite.Domain;
using RecommendationSite.Service;
using Microsoft.AspNetCore.Identity;
namespace RecommendationSite
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration) => Configuration = configuration;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
Configuration.Bind("Project", new Config());
services.AddTransient<ITextFieldsRepository, EFTextFieldsRepository>();
services.AddTransient<IServiceItemsRepository, EFServiceItemsRepository>();
services.AddTransient<DataManager>();
services.AddDbContext<AppDbContext>(x => x.UseSqlServer(Config.ConnectionString));
services.AddIdentity<IdentityUser, IdentityRole>(opts =>
{
opts.User.RequireUniqueEmail = true;
opts.Password.RequiredLength = 6;
opts.Password.RequireNonAlphanumeric = false;
opts.Password.RequireLowercase = false;
opts.Password.RequireUppercase = false;
opts.Password.RequireDigit = false;
}).AddEntityFrameworkStores<AppDbContext>().AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "myCompanyAuth";
options.Cookie.HttpOnly = true;
options.LoginPath = "/account/login";
options.AccessDeniedPath = "/account/accessdenied";
options.SlidingExpiration = true;
});
services.AddControllersWithViews()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0).AddSessionStateTempDataProvider();
services.AddDbContext<RecommendationSiteContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("RecommendationSiteContext")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//else
//{
// app.UseExceptionHandler("/Home/Error");
// // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
// app.UseHsts();
//}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
/*var defaultCulture = new CultureInfo("en-US");
var localizationOptions = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(defaultCulture),
SupportedCultures = new List<CultureInfo> { defaultCulture },
SupportedUICultures = new List<CultureInfo> { defaultCulture },
};
app.UseRequestLocalization(localizationOptions);
var ui = System.Globalization.CultureInfo.CurrentUICulture;*/
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
我是一个新手程序员,我对一些事情感到困惑,也许有人知道原因是什么?
我搜索了所有的论坛,并尝试了许多不同的变体。
答:
0赞
GoldenCave
9/16/2023
#1
异常“值不能为空。参数名称:connectionString“可能是由以下函数抛出的:。
这是一个扩展方法或“帮助程序”方法,专门查找 appsettings.json 文件中以以下模式开头的配置:Configuration.GetConnectionString("RecommendationSiteContext")
"ConnectionStrings": {
"RecommendationSiteContext": "Data Source=.."}
由于 appsettings.json 文件没有该属性,因此它不会找到该部分,然后引发异常。例如,连接字符串当前存储在“Project”JSON 对象中:
"Project": {
"ConnectionStrings": "Data Source==(local)\\SQLSERVER; Database=RecommendationSite; ...
因此,为了修复该特定异常,需要添加一个 json 部分并移过连接字符串,如下所示:
{
"Project": {
"CompanyName": "RecommendationSite1 ",
"CompanyPhone": "+7 (111) 111-11-11",
"CompanyPhoneShort": "+71111111111",
"CompanyEmail": "[email protected]"
},
"ConnectionStrings": {
"RecommendationSiteContext": "Data Source=(local)\\SQLSERVER; Database=RecommendationSite; Persist Security Info=false; User ID='sa'; Password='sa'; MultipleActiveResultSets=True; Trusted_Connection=False;"
}
}
这里有一个类似的问题,但请记住,使用的是旧版本的 .NET,因此可能无法完美翻译。但是,上述建议应该对您有所帮助。值不能为 null。参数名称:starter中的 connectionString appsettings.json
评论