c# - 作为 Windows 服务运行时,ASP.Net Core 2.1 应用程序找不到 appsettings.json

标签 c# asp.net-core .net-core windows-services asp.net-core-2.1

我正在尝试将我的 ASP.Net Core 2.1 应用程序作为一项服务运行在 Windows 10 上。我的应用程序在使用 VS2017 运行时运行良好,或者如果我发布到一个文件夹,然后使用 --控制台参数但是,如果我使用 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 所在的已发布文件夹。这使我认为问题出在作为服务运行时设置当前目录的方式,但我无法准确确定它不起作用的原因。

我已经按照 this Microsoft document 中的说明设置了我的 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 --控制台 应用程序按预期运行。

安装casapi服务以作为本地系统帐户登录。

最佳答案

作为App configuration ,我们需要调用 SetCurrentDirectory 并使用应用程序发布位置的路径。

对于您的问题,您在调用 Directory.SetCurrentDirectory(pathToContentRoot); 之前访问 Directory.GetCurrentDirectory(),因为您调用 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();

关于c# - 作为 Windows 服务运行时,ASP.Net Core 2.1 应用程序找不到 appsettings.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56956349/

相关文章:

c# - 使用 LINQ,如何从列表中查找具有给定属性值的对象?

C# 委托(delegate)给结构方法

asp.net-core - 在 IIS 中运行 Web 应用程序时,HttpContext 为 NULL

.net-core - 将应用洞察跟踪日志记录添加到 .net 核心控制台应用程序

linux - ASP.NET Core Angular 应用程序无法在带有 Nginx 和 Systemd 的 Ubuntu 16.04 上运行

c# - 无法修改 'Selectable.Colors' 的返回值,因为它不是变量

c# - WPF WrapPanel 中的动态项目填充

api - 使用 Swashbuckle V5 从代码生成 swagger.json

使用 HTTP POST 上传 PDF 文件的 VBA

c# - 为什么 "DateTime.Now.ToString("hh tt", new CultureInfo ("de"))"在不同版本的 .Net 中返回不同的结果?