簡體   English   中英

我發布了我的 ASP.NET Core 6 項目,它發布成功,但是當我 run.exe 文件說 ConnectionString 不能是 null

[英]I published my ASP.NET Core 6 project it published successfully, but when I run .exe file that say ConnectionString cannot be null

這是我的代碼:

程序.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:值不能為 null。 (參數“連接字符串”)
在 Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(字符串值,字符串參數名稱)
在 Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action 1 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)
在 Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.CreateDbContextOptions[TContext](IServiceProvider applicationServiceProvider, Action 2 optionsAction) at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass17_0 1.b__0(IServiceProvider p) 在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.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) 在 Microsoft .Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context) 在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.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 ) 在 Microsoft.Extensions.Dep 的 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope 范圍) endencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.b__0(ServiceProviderEngineScope 范圍)在 Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(類型 serviceType,ServiceProviderEngineScope serviceProviderEngineScope)
在 Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) 在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) 在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)在 F:\ProjectAsp.net\es1\es15Incomplete\Espadana\Espadana\Espadana\Program.cs:line 100 中的 Program.$(String[] args)

根據運行時的環境,.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

暫無
暫無

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

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