スポンサーリンク
スポンサーリンク

dotnetコマンドで"connectionString Value cannot be null"エラーが出る原因

.NET Core
VisualStudio 2017 のテンプレートから、「ASP.NET Core Web アプリケーション(MVC)」を選択し、「認証の変更」を「個別のユーザーアカウント」に変更してプロジェクトを新規作成し、ソースコードは何も変更せずに発行したファイル群をCentOSにアップして、dotnetコマンドで実行すると「connectionString Value cannot be null.」エラーが出てハマった。
Web起動

# /usr/bin/dotnet /var/www/WebApplication1/WebApplication1.dll

Web接続確認

# curl http://localhost:5000

Web接続確認すると、Web起動側でエラーが発生する

fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]  An unhandled exception has occurred while executing the request. System.ArgumentNullException: Value cannot be null. Parameter name: connectionString  at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)  at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 sqlServerOptionsAction)  at WebApplication2.Startup.b__4_1(DbContextOptionsBuilder options) in D:\work\VisualStudioテンプレート\WebApplication1\Startup.cs:line 39

環境

OSバージョン:CentOS Linux release 7.6.1810 (Core)
.NetCoreバージョン:2.2.6
Web発行先フォルダ:/var/www/WebApplication1

rootユーザでログインし、カレントディレクトリを変更せずに、dotnetコマンドを実行したことで、appsettings.jsonファイルを読み込めなかったのが原因でした。
カレントディレクトリを、appsettings.jsonファイルがフォルダにすることで解消しました。
エラーが発生しないWeb起動

# cd /var/www/WebApplication1
# /usr/bin/dotnet ./WebApplication1.dll

Startup.cs の起動処理でカレントディレクトリを設定することでも解消できる。

public Startup(IConfiguration configuration)
{
  Environment.CurrentDirectory = “/var/www/WebApplication1/”;

  Configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
    .AddEnvironmentVariables()
    .AddJsonFile(“appsettings.json”, false, true).Build();
}

コメント

タイトルとURLをコピーしました