ASP.Net Core部署为Windows服务的

.net core 版本:2.1

产生的问题:

按照官方的方式将ASP.NET Core部署成WINDOWS服务后,会报以下错误,因为是使用 dotnet.exe 来启动程序,启动目录定位到了c:\windows\system32\下,暂时没有找到怎么切换到程序目录的方法。

Application: dotnet.exe
CoreCLR Version: 4.6.28516.3
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.DirectoryNotFoundException: C:\windows\system32\

解决方法:

1. NuGet引用 Microsoft.AspNetCore.Hosting.WindowsServices

2. 修改Main入口

    public class Program
    {
        public static void Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));

            if (isService)
            {
                var pathToExe = Process.GetCurrentProcess().MainModule.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.RunAsService();
            }
            else
            {
                host.Run();
            }
        }

        private static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseKestrel()
                .ConfigureAppConfiguration((context, builder) =>
                {
                    builder.SetBasePath(context.HostingEnvironment.ContentRootPath)
                        .AddDefaultJsonFile()
                        .AddEnvironmentJsonFile();
                })
                .UseStartup<Startup>();

    }

3. 修改发布设置

将目标运行时改为'win-x64'(或者win-x84),这样发布时会生成 .exe 文件(这个很重要,这样用EXE启动就解决了启动目录定位的问题),可移植方式生成的是 .dll。

4. 服务安装、启动

//安装服务
sc create MyService binPath= "\"D:\App1\MyService.exe\" \"\"" DisplayName= "MyService" start= auto

//启动服务:
sc run MyService

//停止服务:
sc stop MyService

//卸载服务:
sc delete MyService

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值