自包含 ASP.Net 核心未读取 appsettings.json 文件

Self-Contained ASP.Net Core Not Reading appsettings.json file

我写了一个 ASP.Net Core 2.2 应用程序。当我 运行 在我的开发机器上时一切正常。

我已将其作为独立应用程序发布并部署到我的暂存计算机上。

目标框架是netcoreapp2.2。 RuntimeIdentifier 是 win-x64。环境正在升级。

当通过命令行 运行 运行应用程序进行某些测试时,它似乎没有读取 appsettings.staging.json 或任何 appsettings.json 文件。

出于测试目的,我将 Startup.cs 的配置方法设置如下:

public void Configure( IApplicationBuilder app , IHostingEnvironment env )
{
    if( env.IsDevelopment( ) )
    {
        app.UseDeveloperExceptionPage( );
    }
    else
    {
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts( );
    }

    app.UseHttpsRedirection( );

    Console.WriteLine( $"Chris Environment: {env.EnvironmentName}" );
    Console.WriteLine( $"Chris IsStaging: {env.IsStaging( )}" );
    Console.WriteLine( $"Chris ConnectionString: {Configuration.GetConnectionString( "DefaultConnection" )}" );
    Console.WriteLine( $"Chris LoggingAPI: {Configuration["LoggingAPIURL"]}" );

    foreach( var test in Configuration.AsEnumerable( ) )
    {
        var key = test.Key;
        var val = test.Value;
        Console.WriteLine( $"Chris Key: {key} - Value: {val}" );
    }

    app.UseMvc( b =>
    {
        b.Select( ).Expand( ).Filter( ).OrderBy( ).MaxTop( 100 ).Count( );
        b.MapODataServiceRoute( "default" , "api" , EdmModelBuilder.GetEdmModel( app.ApplicationServices ) );
    } );
}

我 运行 通过在命令行中键入应用程序:path/To/My/App.exe --environment Staging

写出的结果是: 克里斯环境:分期 Chirs IsStaging:正确 克里斯连接字符串: 克里斯 LoggingAPI:

connectionstring 和 LoggingAPI 留空。循环 returns 一堆值,但 appsettings.json 文件中没有任何值。

我的 appsettings.json 文件如下所示:

{
  "ConnectionStrings": {
    "DefaultConnection": "Some ConnectionString"
  },
 "Logging": {
   "LogLevel": {
     "Default": "Warning"
   }
  },
   "AllowedHosts": "*",
   "LoggingAPIURL": "SomeURL"
}

我已验证 appsetting.json 文件在服务器上。

谁能给我解释一下这是怎么回事?

WebHostBuilder 配置的基本路径设置为 IHostingEnvironment.ContentRootPath (source):

var builder = new ConfigurationBuilder()            
    .SetBasePath(_hostingEnvironment.ContentRootPath)

当使用 WebHostBuilder.CreateDefaultBuilder 时,这是项目模板生成的默认方法,IHostingEvironment.ContentRootPath 使用 Directory.GetCurrentDirectory() (source):

设置
builder.UseContentRoot(Directory.GetCurrentDirectory());

这意味着,当尝试定位 appsettings.jsonappsettings.[Environment].json 时,会使用 工作目录 而不一定是应用程序的目录。在您的示例中,您 运行 从其自己的目录外部启动应用程序,这意味着未找到 .json 文件。

要解决此问题,您可以先 cdpath/To/My,然后从那里 运行 App.exe。或者,如果您要 运行 App.exe 作为一项服务,您可以将工作目录设置为与应用程序本身相同的目录。