如果在发布文件夹外执行 dotnet,则 dotnet 不会加载 appsettings.json

dotnet not loading appsettings.json if executing dotnet outside publish folder

我已经在这个问题上徘徊了很长一段时间,但仍然没有找到答案,也没有另一个 post 处理同样的问题。

我已经发布了一个 .net 5.0 网站,如果我 运行 dotnet 在同一个发布的文件夹中,一切正常。在此文件夹中,我还有一个名为 appsettings.json 的文件,其中包含应用程序所需的所有配置,即:

+ path
 + to
   + karinapi
     - MinosIT.Karin.API.dll
     - appsettings.json

当我在文件夹中 运行 dotnet 时,一切正常,读取设置没有任何问题:

cd /path/to/karinapi
dotnet MinosIT.Karin.API.dll

结果还可以即:

user@machine$ dotnet MinosIT.Karin.API.dll
info: MinosIT.Karin.API.Program[0]
      Inicializando migración
info: MinosIT.Karin.Migrations.HDIKarinMigrations[0]
      Verificando migraci+on
info: MinosIT.Karin.Migrations.HDIKarinMigrations[0]
      Checking whether journal table exists..
info: MinosIT.Karin.Migrations.HDIKarinMigrations[0]
      Fetching list of already executed scripts.
info: MinosIT.Karin.API.Program[0]
      finalizando migración     

但是当我尝试遵循本指南时: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-nginx?view=aspnetcore-5.0 它说你必须创建一个服务和 运行 像这样的应用程序

/usr/bin/dotnet /path/to/karinapi/MinosIT.Karin.API.dll

问题是,当我在发布文件夹之外尝试 运行 我的应用程序时,dotnet 似乎找不到 appsettings.json 文件,即:

user@mymachine$ pwd
/path/to/
user@mymachine$ /user/bin/dotnet /path/to/karinapi/MinosIT.Karin.API.dll

应用程序失败并抛出此错误:

 user@mymachine$ dotnet karinapi/MinosIT.Karin.API.dll

Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'implementationInstance')

at Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton[TService](IServiceCollection services, TService implementationInstance)
at MinosIT.Karin.API.Startup.ConfigureServices(IServiceCollection services) in D:\Minos IT\Karin\MinosIT.Karin\BackEnd\MinosIT.Karin.api\Startup.cs:line 72
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) in /_/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs:line 399
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass9_0.g__Startup|0(IServiceCollection serviceCollection)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass8_0.b__0(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services, Object instance)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass13_0.b__0(HostBuilderContext context, IServiceCollection services)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()

我正在使用 Microsoft.Extensions.Configuration

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

    public IConfiguration Configuration { get; }
    ...

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

StartUp.ConfigureServices 里面,我正在使用:

var connectionString = Configuration.GetConnectionString("ConnectionStringName");
var section = Configuration.GetSection("CustomSection").Get<CustomConfiguration>();

当我调试时,我的代码通过日志记录我明白问题可能是 ASP.NET 核心不知道在哪里阅读 appsettings.json,我查看了 dotnet cli 文档,环境变量,其他配置类型,我似乎找不到问题。我真的不知道还要寻找什么,任何指导或帮助将不胜感激。

在此先感谢您的帮助。

找到了解决方案,我在这里发帖以防其他人遇到同样的错误:

里面 Program.cs 我改自:

        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }
                );

        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, config) =>
                {
                    var assembly = Assembly.GetExecutingAssembly();
                    var currentPath = System.IO.Path.GetDirectoryName(assembly.Location);

                    config.SetBasePath(currentPath);
                    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }
                );