asp.net core3.1修改代码以支持windows服务发布

实际上官网也已经给出了一个步骤:https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-3.1&tabs=visual-studio

但是我这边测试了一下,感觉好像不行,于是按自己的思路进行了实现,具体操作步骤如下

一、引入nuget

需要引入如下两个包:

<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="3.1.21" />
<PackageReference Include="Microsoft.Extensions.Logging.EventLog" Version="3.1.21" />

二、调整Program文件

首先需要引入命名空间:using Microsoft.Extensions.Hosting;

然后调整代码如下:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    var host = Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

    if (!(args.Contains("--console") || Debugger.IsAttached))
    {
        var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
        var pathToContentRoot = Path.GetDirectoryName(pathToExe);
        Directory.SetCurrentDirectory(pathToContentRoot);//指定当前工作目录,不然会被定义到system32下面去
        host.UseWindowsService();//核心代码
    }
    return host;
}

三、发布

编译成功之后就需要发布到windows服务,打开命令窗口执行如下命令:

sc.exe create siteinfo BinPath=E:\duanjt\SiteInfo\trunk\SiteInfo\SiteInfo\bin\Release\netcoreapp3.1\SiteInfo.exe

注意:是sc.exe。博主看有的地方使用的sc,但是博主尝试多次都没有成功。另外,如果路径中包含空格,请使用引号""包含。(后来发现如果是powershell就需要sc.exe。dos可以不用exe后缀)

启动/停止/删除服务

net start siteinfo//启动服务
net stop siteinfo//停止服务
sc.exe delete siteinfo //卸载服务

 四、制作bat文件

输入命令有时候会比较繁琐,因此我们可以制作成批处理文件放到exe文件同级,安装.bat 内容如下:

@echo off 
@title 安装工位管理系统
@echo off 
echo= 安装服务!
@echo off  
@sc create siteinfo binPath= "%~dp0SiteInfo.exe"  
echo= 启动服务!
@echo off  
@sc start siteinfo 
@echo off  
echo= 配置服务! 
@echo off  
@sc config siteinfo start= AUTO  
@echo off  
echo= 成功安装、启动、配置服务!   
@pause

注意:bat文件的编码必须是ANSI,否则可能出现乱码

原文地址:https://www.cnblogs.com/duanjt/p/15563867.html