Search code examples
c#.net-core.net-5asp.net-core-5.0

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


Here is my code:

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"
  }
}

Error:

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_02.b__0(IServiceProvider p, DbContextOptionsBuilder b)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.CreateDbContextOptions[TContext](IServiceProvider applicationServiceProvider, Action2 optionsAction) at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass17_01.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.CallSiteVisitor2.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.CallSiteVisitor2.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


Solution

  • Depending on the environment of the runtime, .net looks for different settings files. So if your environment is staging, .net looks for appsettings.staging.json. In VS debug mode, the default is appsettings.development.json. In your cases the environment of the machine is set to something else.

    To fix this issue, you can do one of these

    1. change the environment of the machine where you are publishing the exe to development
    2. add a file called appsettings.xxxxxx.json where 'xxxxxx' is the environment of the machine
    3. If you have common connection string for both dev and publish (HIGHLY DISCOURAGED) you can put your connection credentials in appsettings.json

    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0

    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-6.0