Search code examples
c#asp.net-core.net-coredotnet-cli

Running a published version of an asp.net core from the cli


Having issues when running a Release configuration version of an asp.net core app from the cli.

The app is very simple, I've created a new Asp.Net with the Api template, so I get the weatherforecast app.

I've added a SqlServer project, using Entity Framework core and I'm configuring it using a connectionString taken from an appsettings.Production.json file

  "ConnectionString": {
    "SqlServer": "Server = .; Database = test_Prod; Trusted_Connection = True; "
  },

My Startup class constructor

    public Startup(IWebHostEnvironment environment)
    {
        _configurationRoot = new ConfigurationBuilder()
            .SetBasePath(environment.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{ environment.EnvironmentName }.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();

        _environment = environment;
    }

and the Configuration method

    public void Configure(IApplicationBuilder app, ILogger<Startup> logger)
    {
        if (_environment.IsProduction())

            logger.LogInformation($" { Environment.NewLine } Environment { _environment.EnvironmentName } launched { Environment.NewLine }");

            logger.LogInformation($" ConnectionString : { _configurationRoot.GetSection("ConnectionString").GetValue<string>("SqlServer") }");            { 

            AppContext dbContext = app.ApplicationServices.GetRequiredService<AppContext>();
        }

I'm getting the following exception

crit: Microsoft.AspNetCore.Hosting.Diagnostics[6]
      Application startup 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 optionsBuil

Inspecting my logs I get Environment is Production and ConnectionString is empty

Following are the commands that I'm executing

  1. dotnet publish -c Release -o out

  2. dotnet .\out\myApp.dll

What am I doing wrong ?

The app works if ran from Visual Studio and also if ran from the dotnet cli using run command

dotnet run -p .\myApp\myApp.csproj


Solution

    1. You need to ensure the appsettings.json or appsettings.production.json are physically present in your published folder
    2. If your connection string is in the appsettings.production.json you need to go to your System Environment Variables (Start > Run > rundll32.exe sysdm.cpl,EditEnvironmentVariables) and manually set ASPNETCORE_ENVIRONMENT variable to PRODUCTION. Remember Visual Studio transiently adds that environment variable while running your app.
    3. An alternate to step 2 would be to move your Connection String to appsettings.json