![](/img/trans.png)
[英]ASP.NET Core 2.1 application not getting correct appsettings.json
[英]ASP.Net Core 2.1 application cannot find appsettings.json when ran as a Windows service
我正在嘗試將我的 ASP.Net Core 2.1 應用程序作為 Windows 10 上的服務運行。我的應用程序在使用 VS2017 運行時運行良好,或者如果我發布到一個文件夾,然后使用 --console 參數從該發布的文件夾中啟動它。 但是,如果我使用 sc create 創建服務,獲得成功結果,然后嘗試運行它,我會在 Windows 應用程序日志中收到一條錯誤消息,指出...
System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\WINDOWS\system32\appsettings.json'.
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
我已確認我的 appsettings.json 文件存在於已發布的文件夾中。 該錯誤消息指出正在 C:\\WINDOWS\\system32\\ 文件夾中查找 appsettings.json 文件,而不是應用程序 .exe 所在的已發布文件夾。 這讓我認為問題在於作為服務運行時當前目錄的設置方式,但我無法確定它為什么不起作用。
我已按照此 Microsoft 文檔中的說明設置了我的 Program.cs。 我的 program.cs 如下所示;
public class Program
{
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddUserSecrets<Startup>()
.Build();
public static void Main(string[] args)
{
ConfigureSerilog();
// Set up to run as a service if not in Debug mode or if a command line argument is not --console
var isService = !(Debugger.IsAttached || args.Contains("--console"));
if (isService)
{
var processModule = Process.GetCurrentProcess().MainModule;
if (processModule != null)
{
var pathToExe = processModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
Directory.SetCurrentDirectory(pathToContentRoot);
}
}
var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray());
var host = builder.Build();
if (isService)
{
host.RunAsCustomService();
}
else
{
try
{
Log.Information("Starting CAS API in Program.cs");
host.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "CAS API Host terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) => { logging.AddEventSourceLogger(); })
.ConfigureAppConfiguration((context, config) =>
{
// Configure the app here.
})
.UseStartup<Startup>()
.UseSerilog()
.UseUrls("https://localhost:60026"); //This is only used when ran as a stand-alone service. Not in VisualStudio
private static void ConfigureSerilog()
{
// Set up Serilog
var connectionString = Configuration.GetConnectionString("CasDbConnectionString");
const string tableName = "Logs";
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Filter.ByExcluding(Matching.FromSource("Microsoft.EntityFrameworkCore.Query"))
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithThreadId()
.Enrich.WithUtcTimeStamp()
.Enrich.WithProperty("Application", $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}")
.Enrich.FromLogContext()
.CreateLogger();
}
我試過更換...
host.RunAsCustomeService();
和 ...
host.RunAsService();
我仍然有同樣的問題。
我正在運行 sc 命令,如下所示;
sc create casapi start= auto binPath= c:\deployments\casapi\casapi.exe
我看到 Windows 服務中列出了 casapi 服務。 但是如果我運行 sc 命令...
sc start casapi
我收到上面指出的錯誤。
如果我在提升的命令提示符中轉到已發布的文件夾並鍵入... casapi.exe --console 應用程序按預期運行。
casapi 服務安裝到作為本地系統帳戶登錄。
作為應用配置,我們需要調用 SetCurrentDirectory 並使用應用發布位置的路徑。
對於您的問題,您在調用Directory.SetCurrentDirectory(pathToContentRoot);
之前訪問Directory.GetCurrentDirectory()
Directory.SetCurrentDirectory(pathToContentRoot);
當你調用ConfigureSerilog();
第一的。
嘗試更改順序
// Set up to run as a service if not in Debug mode or if a command line argument is not --console
var isService = !(Debugger.IsAttached || args.Contains("--console"));
if (isService)
{
var processModule = Process.GetCurrentProcess().MainModule;
if (processModule != null)
{
var pathToExe = processModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
Directory.SetCurrentDirectory(pathToContentRoot);
}
}
ConfigureSerilog();
嘗試這個。
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.