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

时间:2019-07-09 15:49:25

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

我正在尝试在Windows 10上将ASP.Net Core 2.1应用程序作为服务运行。使用VS2017运行时,或者如果我发布到某个文件夹,然后使用-从该发布的文件夹中启动它,我的应用程序运行良好。控制台参数但是,如果我使用sc create创建服务,获得成功结果,然后尝试运行它,则Windows应用程序日志中将显示错误消息,说明...

const regex = /\{\{(.*?)\}\}\s*((?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~.+-])+@(?:(?:[A-Za-z0-9-])+?\.)+(?:[A-Za-z0-9]{2,})+)\s*\{\{\/(\1)\}\}/sg;
const str = `{{foreach}} mail-1@mail.com  {{/foreach}}
{{foreach}} mail-2@mail.com{{/foreach}}
{{foreach}} 
	mail-3@mail.com
{{/foreach}}
					`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

我已确认我的appsettings.json文件存在于已发布的文件夹中。 错误消息指出正在C:\ WINDOWS \ system32 \文件夹中查找appsettings.json文件,而不是应用程序.exe所在的已发布文件夹。这使我认为问题出在作为服务运行时设置当前目录的方式,但是我很难确定它为什么不起作用。

我已经按照this Microsoft document中的说明设置了Program.cs。我的program.cs如下所示;

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)   

我尝试更换...

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();

我仍然有同样的问题。

我正在按以下方式运行sc命令;

host.RunAsService();

我看到Windows服务中列出了casapi服务。但是如果我运行sc命令...

sc create casapi start= auto binPath= c:\deployments\casapi\casapi.exe

我得到上面指出的错误。

如果我在提升权限的命令提示符下转到发布的文件夹,然后键入...     casapi.exe-控制台 该应用程序按预期运行。

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

3 个答案:

答案 0 :(得分:3)

如果使用的是Task Scheduler,则可以将所需的目录写入

操作标签->编辑->开始于

因此程序将从该目录开始运行。 enter image description here

答案 1 :(得分:2)

App configuration一样,我们需要调用SetCurrentDirectory并使用指向应用程序发布位置的路径。

对于您的问题,请先访问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();

答案 2 :(得分:0)

尝试一下。

  application: