【问题标题】:I published my ASP.NET Core 6 project it published successfully, but when I run .exe file that say ConnectionString cannot be null我发布了我的 ASP.NET Core 6 项目,它发布成功,但是当我运行 .exe 文件时说 ConnectionString 不能为空
【发布时间】:2022-01-27 22:22:41
【问题描述】:

这是我的代码:

程序.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"
  }
}

错误:

未处理的异常。 System.ArgumentNullException:值不能 空值。 (参数'connectionString')
在 Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(字符串值,字符串参数名称)
在 Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder,字符串 connectionString,Action1 sqlServerOptionsAction) at AccountManagement.Configuration.AccountBootstrapper.&lt;&gt;c__DisplayClass0_0.&lt;Configure&gt;b__0(DbContextOptionsBuilder c) in F:\ProjectAsp.net\es1\es15Incomplete\Espadana\Espadana\AccountManagement.Configuration\AccountBootstrapper.cs:line 19 at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.&lt;&gt;c__DisplayClass1_02.b__0(IServiceProvider p,DbContextOptionsBuilder b)
在 Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.CreateDbContextOptions[TContext](IServiceProvider applicationServiceProvider, Action2 optionsAction) at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.&lt;&gt;c__DisplayClass17_01.b__0(IServiceProvider p) 在 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.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument 参数)在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite,RuntimeResolverContext 上下文)在 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.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument 参数)在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite,ServiceProviderEngineScope 范围)在 Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.c__DisplayClass2_0.b__0(ServiceProviderEngineScope 范围)在 Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(类型 serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
在 Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(类型 服务类型)在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider 提供者,类型 serviceType) 在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider 提供者)在 Program.$(String[] args) 中 F:\ProjectAsp.net\es1\es15Incomplete\Espadana\Espadana\Espadana\Program.cs:line 100

【问题讨论】:

    标签: c# .net-core .net-5 asp.net-core-5.0


    【解决方案1】:

    根据运行时的环境,.net 会查找不同的设置文件。因此,如果您的环境是staging,.net 会查找appsettings.staging.json。在 VS 调试模式下,默认为appsettings.development.json。在您的情况下,机器的环境设置为其他内容。

    要解决此问题,您可以执行以下操作之一

    1. 更改要发布 exe 以进行开发的机器的环境
    2. 添加一个名为 appsettings.xxxxxx.json 的文件,其中 'xxxxxx' 是机器的环境
    3. 如果您有用于开发和发布的通用连接字符串(强烈反对),您可以将您的连接凭据放在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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-10
      • 2021-10-02
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      相关资源
      最近更新 更多