Unhandled exception. System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional

В общем, вызываю в Main:

var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
Directory.SetCurrentDirectory(Path.GetDirectoryName(pathToExe));

А далее метод:

public static IWebHostBuilder CreateHostBuilder(string[] args, bool isService)
{
    var config = new ConfigurationBuilder()
        .AddEnvironmentVariables()
        .AddInMemoryCollection(new[] { new KeyValuePair<string, string>("IsService", isService.ToString()) })
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();
    
    return WebHost.CreateDefaultBuilder(args).ConfigureLogging((context, logging) =>
        {
            logging.ClearProviders();
            logging.AddSerilog(new LoggerConfiguration()
                .ReadFrom.Configuration(context.Configuration)
                .CreateLogger());
        })
        .UseConfiguration(config)
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIIS()
        .UseStartup<Startup>();
}

И когда пытаюсь все это запустить в IIS, то ловлю ошибку:

Unhandled exception. System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'c:\windows\system32\inetsrv\appsettings.json'.

Почему он ищет конфигурационный файл не в той папке? Я же указал путь к базовой директории...


Ответы (1 шт):

Автор решения: iluxa1810

Как я понял, так как я хостю это дело все внутри процесса IIS, то

Process.GetCurrentProcess().MainModule.FileName

Показывает путь к IIS'у.

Я сменил метод определения базовой директории на:

new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath

И все заработало.

Правда, не понимаю 1 момента:

Почему при дебаге там отображается путь к исполняемому файлу, а когда из под IIS запускаешь, то туда попадает путь к директории...

Буду признателен за пояснение в комментариях.

→ Ссылка