我发布了我的 ASP.NET Core 6 项目,它发布成功了,但是当我 运行 .exe 文件说 ConnectionString cannot be null
I published my ASP.NET Core 6 project it published successfully, but when I run .exe file that say ConnectionString cannot be null
这是我的代码:
Program.cs :
using _0_FrameWork;
using _0_FrameWork.FrameWorkApplication;
using _0_FrameWork.Infrastructure;
using AccountManagement.Configuration;
using AccountManagement.Infrastructure;
using Espadana;
using Invoice.Configuration;
using Invoice.Infrastructure;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddHttpContextAccessor();
builder.Services.AddAntiforgery(o => o.HeaderName = "CSRF-TOKEN");
var connectionString = builder.Configuration.GetConnectionString("ESDb");
builder.Services.AddDbContext<ApplicationContext>(c => c.UseSqlServer(connectionString));
builder.Services.AddSingleton<IPasswordHasher, PasswordHasher>();
builder.Services.AddTransient<IFileUploader, FileUploader>();
builder.Services.AddTransient<IAuthHelper, AuthHelper>();
builder.Services.AddTransient<IApplicationManager, ApplicationManager>();
InvoiceBootstrapper.Configure(builder.Services, connectionString);
AccountBootstrapper.Configure(builder.Services, connectionString);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddMvcCore(c => c.EnableEndpointRouting=false);
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Lax;
});
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
{
o.LoginPath = new PathString("/Login");
o.LogoutPath = new PathString("/Login");
o.AccessDeniedPath = new PathString("/Login");
});
builder.Services.AddAuthorization(option =>
{
option.AddPolicy("Account",
builder => builder.RequireRole(new List<string> { Roles.Administrator })
);
option.AddPolicy("Invoice",
builder => builder.RequireRole(new List<string> { Roles.UserSystem, Roles.Administrator })
);
});
builder.Services.AddRazorPages()
.AddMvcOptions(option => option.Filters.Add<SecurityPageFilter>())
.AddRazorPagesOptions(option =>
{
option.Conventions.AuthorizeFolder("/Invoice", "Invoice");
option.Conventions.AuthorizeFolder("/AccountPages", "Account");
option.Conventions.AuthorizePage("/Index", "Account");
}
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<AccountContext>();
context.Database.EnsureCreated();
DbInitializer.Initialize(context);
var contextI = services.GetRequiredService<InvoiceContext>();
contextI.Database.EnsureCreated();
}
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvc();
app.UseRouting();
app.MapRazorPages();
app.Run();
appsettings.Development.json
:
{
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"ESDb": "Data Source=.;Initial Catalog=ES;User ID=sa;Password =123456"
}
}
错误:
Unhandled exception. System.ArgumentNullException: Value cannot be
null. (Parameter 'connectionString')
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action1 sqlServerOptionsAction) at AccountManagement.Configuration.AccountBootstrapper.<>c__DisplayClass0_0.<Configure>b__0(DbContextOptionsBuilder c) in F:\ProjectAsp.net\es1\es15Incomplete\Espadana\Espadana\AccountManagement.Configuration\AccountBootstrapper.cs:line 19 at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass1_0
2.b__0(IServiceProvider p, DbContextOptionsBuilder b)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.CreateDbContextOptions[TContext](IServiceProvider applicationServiceProvider, Action2 optionsAction) at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass17_0
1.b__0(IServiceProvider
p) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(ServiceCallSite
callSite, TArgument argument) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite
constructorCallSite, RuntimeResolverContext context) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(ServiceCallSite
callSite, TArgument argument) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite
callSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.b__0(ServiceProviderEngineScope
scope) at
Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type
serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type
serviceType) at
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider
provider, Type serviceType) at
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider
provider) at Program.$(String[] args) in
F:\ProjectAsp.net\es1\es15Incomplete\Espadana\Espadana\Espadana\Program.cs:line
100
根据运行时的环境,.net 会寻找不同的设置文件。因此,如果您的环境是 staging
,.net 会寻找 appsettings.staging.json
。在VS调试模式下,默认为appsettings.development.json
。在您的情况下,机器的环境设置为其他内容。
要解决此问题,您可以执行以下操作之一
- 更改要发布 exe 的机器环境以进行开发
- 添加一个名为
appsettings.xxxxxx.json
的文件,其中 'xxxxxx' 是机器的环境
- 如果您有用于开发和发布的通用连接字符串(强烈反对),您可以将您的连接凭据放入
appsettings.json
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-6.0
这是我的代码:
Program.cs :
using _0_FrameWork;
using _0_FrameWork.FrameWorkApplication;
using _0_FrameWork.Infrastructure;
using AccountManagement.Configuration;
using AccountManagement.Infrastructure;
using Espadana;
using Invoice.Configuration;
using Invoice.Infrastructure;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddHttpContextAccessor();
builder.Services.AddAntiforgery(o => o.HeaderName = "CSRF-TOKEN");
var connectionString = builder.Configuration.GetConnectionString("ESDb");
builder.Services.AddDbContext<ApplicationContext>(c => c.UseSqlServer(connectionString));
builder.Services.AddSingleton<IPasswordHasher, PasswordHasher>();
builder.Services.AddTransient<IFileUploader, FileUploader>();
builder.Services.AddTransient<IAuthHelper, AuthHelper>();
builder.Services.AddTransient<IApplicationManager, ApplicationManager>();
InvoiceBootstrapper.Configure(builder.Services, connectionString);
AccountBootstrapper.Configure(builder.Services, connectionString);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddMvcCore(c => c.EnableEndpointRouting=false);
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.Lax;
});
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
{
o.LoginPath = new PathString("/Login");
o.LogoutPath = new PathString("/Login");
o.AccessDeniedPath = new PathString("/Login");
});
builder.Services.AddAuthorization(option =>
{
option.AddPolicy("Account",
builder => builder.RequireRole(new List<string> { Roles.Administrator })
);
option.AddPolicy("Invoice",
builder => builder.RequireRole(new List<string> { Roles.UserSystem, Roles.Administrator })
);
});
builder.Services.AddRazorPages()
.AddMvcOptions(option => option.Filters.Add<SecurityPageFilter>())
.AddRazorPagesOptions(option =>
{
option.Conventions.AuthorizeFolder("/Invoice", "Invoice");
option.Conventions.AuthorizeFolder("/AccountPages", "Account");
option.Conventions.AuthorizePage("/Index", "Account");
}
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<AccountContext>();
context.Database.EnsureCreated();
DbInitializer.Initialize(context);
var contextI = services.GetRequiredService<InvoiceContext>();
contextI.Database.EnsureCreated();
}
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvc();
app.UseRouting();
app.MapRazorPages();
app.Run();
appsettings.Development.json
:
{
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"ESDb": "Data Source=.;Initial Catalog=ES;User ID=sa;Password =123456"
}
}
错误:
Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action1 sqlServerOptionsAction) at AccountManagement.Configuration.AccountBootstrapper.<>c__DisplayClass0_0.<Configure>b__0(DbContextOptionsBuilder c) in F:\ProjectAsp.net\es1\es15Incomplete\Espadana\Espadana\AccountManagement.Configuration\AccountBootstrapper.cs:line 19 at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass1_0
2.b__0(IServiceProvider p, DbContextOptionsBuilder b)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.CreateDbContextOptions[TContext](IServiceProvider applicationServiceProvider, Action2 optionsAction) at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass17_0
1.b__0(IServiceProvider p) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.b__0(ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Program.$(String[] args) in F:\ProjectAsp.net\es1\es15Incomplete\Espadana\Espadana\Espadana\Program.cs:line 100
根据运行时的环境,.net 会寻找不同的设置文件。因此,如果您的环境是 staging
,.net 会寻找 appsettings.staging.json
。在VS调试模式下,默认为appsettings.development.json
。在您的情况下,机器的环境设置为其他内容。
要解决此问题,您可以执行以下操作之一
- 更改要发布 exe 的机器环境以进行开发
- 添加一个名为
appsettings.xxxxxx.json
的文件,其中 'xxxxxx' 是机器的环境 - 如果您有用于开发和发布的通用连接字符串(强烈反对),您可以将您的连接凭据放入
appsettings.json
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-6.0