Skip to content

Commit 7754c6b

Browse files
config file loading fix
1 parent c7b8230 commit 7754c6b

1 file changed

Lines changed: 18 additions & 2 deletions

File tree

TransactionProcessing.MerchantPos/Program.cs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
using Microsoft.Extensions.Configuration;
55
using Microsoft.Extensions.Hosting;
66
using SecurityService.Client;
7+
using System;
78
using System.Collections.Concurrent;
9+
using System.IO;
810
using System.Text.Json;
911
using NLog;
1012
using NLog.Extensions.Logging;
@@ -24,20 +26,26 @@
2426
?? Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")
2527
?? Environments.Production;
2628

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+
2734
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
2835
{
2936
Args = args,
30-
ContentRootPath = Directory.GetCurrentDirectory(),
37+
ContentRootPath = contentRoot,
3138
EnvironmentName = envName
3239
});
3340

3441
// Load hosting.json so values such as "urls" or Kestrel endpoints are applied
3542
builder.Configuration.AddJsonFile("hosting.json", optional: true, reloadOnChange: true);
3643

3744
// 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.
3846
builder.Configuration
3947
.SetBasePath(builder.Environment.ContentRootPath)
40-
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
48+
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
4149
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
4250
.AddEnvironmentVariables()
4351
.AddCommandLine(args);
@@ -101,6 +109,14 @@
101109
// --- Build the web app (this replaces ConfigureWebHostDefaults) ---
102110
var app = builder.Build();
103111

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+
104120
// Auto-create SQLite database and tables
105121
using (var scope = app.Services.CreateScope())
106122
{

0 commit comments

Comments
 (0)