栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

ASP.Net Core部署为Windows服务的

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ASP.Net Core部署为Windows服务的

.net core 版本:2.1

产生的问题:

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

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:windowssystem32

解决方法:

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

    }

3. 修改发布设置

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

4. 服务安装、启动

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

//启动服务:
sc run MyService

//停止服务:
sc stop MyService

//卸载服务:
sc delete MyService

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/909805.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号