ASP.Net Core不自动读取appsettings.json文件

10
我写了一个ASP.Net Core 2.2应用程序。在我本地运行时一切正常。
我已经发布并将其部署到我的测试机器上,作为一个自包含的应用程序。
目标框架是netcoreapp2.2。RuntimeIdentifier是win-x64。环境是Staging。
当通过命令行运行应用程序进行测试时,似乎没有读取appsettings.staging.json或任何appsettings.json文件。
为了测试目的,我将Startup.cs的Configure方法设置如下:
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

输出结果如下: Chris Environment: Staging Chris IsStaging: True Chris ConnectionString: Chris LoggingAPI:

ConnectionString和LoggingAPI为空白。循环返回许多值,但没有任何在appsettings.json文件中的值。

我的appsettings.json文件如下:

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

我已经确认了appsetting.json文件已经在服务器上。
有人能给我解释一下发生了什么事吗?
1个回答

21

WebHostBuilder 配置的基础路径设置为 IHostingEnvironment.ContentRootPath (来源):

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

当使用WebHostBuilder.CreateDefaultBuilder时,这是项目模板生成的默认方法,IHostingEvironment.ContentRootPath会使用Directory.GetCurrentDirectory()进行设置(源代码):

builder.UseContentRoot(Directory.GetCurrentDirectory());
这意味着在尝试定位appsettings.jsonappsettings.[Environment].json时,将使用工作目录而不一定是应用程序的目录。在您的示例中,您正在应用程序所在的目录之外运行该应用程序,这意味着无法找到.json文件。

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


2
建议在许多关于“我的配置部分为空”等问题的问题中广泛推广这个黄金答案。 - Nick Kovalsky
1
.NET 6仍然是正确的选择。这个答案解释了为什么我不能使用完整路径从命令提示窗口运行我的应用程序,例如 cmd /c "C:\Outbound\MyAppName\MyAppName.exe" (它无法以这种方式找到appsettings.json文件)。根据您的答案,当我将命令写成 cd "C:\Outbound\MyAppName" && cmd /c MyAppName.exe 时,它完美地工作了。 - Phil Nicholas
你的解决方案帮我解决了Linux CentOS和.Net6的问题。谢谢! - Max Vargas
1
谢谢 @PhilNicholas - Marcel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接