|
4 | 4 | using Microsoft.Extensions.Configuration; |
5 | 5 | using Microsoft.Extensions.Hosting; |
6 | 6 | using SecurityService.Client; |
| 7 | +using System; |
7 | 8 | using System.Collections.Concurrent; |
| 9 | +using System.IO; |
8 | 10 | using System.Text.Json; |
9 | 11 | using NLog; |
10 | 12 | using NLog.Extensions.Logging; |
|
24 | 26 | ?? Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") |
25 | 27 | ?? Environments.Production; |
26 | 28 |
|
| 29 | + // IMPORTANT: use the application's folder (not process working dir) as the ContentRootPath. |
| 30 | + // When running as a service the current directory is often C:\Windows\System32 which causes the |
| 31 | + // "appsettings.json not found" error. |
| 32 | + var contentRoot = AppContext.BaseDirectory; |
| 33 | + |
27 | 34 | var builder = WebApplication.CreateBuilder(new WebApplicationOptions |
28 | 35 | { |
29 | 36 | Args = args, |
30 | | - ContentRootPath = Directory.GetCurrentDirectory(), |
| 37 | + ContentRootPath = contentRoot, |
31 | 38 | EnvironmentName = envName |
32 | 39 | }); |
33 | 40 |
|
34 | 41 | // Load hosting.json so values such as "urls" or Kestrel endpoints are applied |
35 | 42 | builder.Configuration.AddJsonFile("hosting.json", optional: true, reloadOnChange: true); |
36 | 43 |
|
37 | 44 | // Explicit configuration ordering: appsettings.json, appsettings.{Environment}.json, environment vars, command line |
| 45 | + // Make appsettings.json optional to avoid hard crash when missing; log a warning instead. |
38 | 46 | builder.Configuration |
39 | 47 | .SetBasePath(builder.Environment.ContentRootPath) |
40 | | - .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) |
| 48 | + .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) |
41 | 49 | .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true) |
42 | 50 | .AddEnvironmentVariables() |
43 | 51 | .AddCommandLine(args); |
|
101 | 109 | // --- Build the web app (this replaces ConfigureWebHostDefaults) --- |
102 | 110 | var app = builder.Build(); |
103 | 111 |
|
| 112 | + // If appsettings.json was missing, log a warning so the deployment issue is visible |
| 113 | + var cfgFile = Path.Combine(builder.Environment.ContentRootPath, "appsettings.json"); |
| 114 | + if (!File.Exists(cfgFile)) |
| 115 | + { |
| 116 | + var warnLogger = app.Services.GetRequiredService<Microsoft.Extensions.Logging.ILogger<Program>>(); |
| 117 | + warnLogger.LogWarning("appsettings.json was not found at {Path}. Using defaults and environment variables.", cfgFile); |
| 118 | + } |
| 119 | + |
104 | 120 | // Auto-create SQLite database and tables |
105 | 121 | using (var scope = app.Services.CreateScope()) |
106 | 122 | { |
|
0 commit comments