.Net Web API应用部署成windows服务

文章目录

有时候会有将.Net Web API应用部署成windows服务的需求,

有2个包可以实现:

官方包:Microsoft.Extensions.Hosting.WindowsServices

第三方包:Topshelf

这篇文章记录官方包的使用方法:

经过测试,使用官方包 .Net6和.Net7部署成Windows服务后启动都会报错,一直升到.Net8才能正常启动。代码没有任何改动。

结论:.NET 8+之后的版本使用官方包,之前的版本使用Topshelf。

1.添加NuGet包:

csharp 复制代码
Microsoft.Extensions.Hosting.WindowsServices

2.修改Program.cs:

csharp 复制代码
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWindowsService(); // 启用WindowsService集成

3.发布应用程序

部署模式:独立,目标运行时:win-x64

4.安装与管理 Windows 服务

以管理员身份打开 PowerShell 或 CMD 执行命令

安装服务:

bash 复制代码
sc.exe create "你的服务名" binPath="C:/MyApiService/你的应用.exe" start= auto DisplayName="你的服务显示名称"

设置服务描述description

bash 复制代码
sc.exe description "你的服务名" "服务描述信息"

启动服务:

bash 复制代码
sc.exe start "你的服务名"

查看状态:

bash 复制代码
sc.exe query "你的服务名"

停止服务:

bash 复制代码
sc.exe stop "你的服务名"

卸载服务(停止后执行):

bash 复制代码
sc.exe delete "你的服务名"

指定Web API监听端口,2种方式

第一种方式,在程序的 appsettings.json 配置文件中配置:

csharp 复制代码
"Kestrel": {
  "Endpoints": {
    "Http": {
      "Url": "http://0.0.0.0:10101"
    }
  }
}

第二种方式,在启动程序时用命令行启动参数指定端口:

通过dll文件启动:

bash 复制代码
dotnet YourApp.dll --urls "http://*:10101"

通过exe文件启动:

bash 复制代码
YourApp.exe --urls "http://*:10101"

通过Windows服务启动:

bash 复制代码
sc config "你的服务名" binPath= "C:/MyApiService/你的应用.exe" --urls http://*:10101"

验证配置:

启动应用后,在主机上运行:

bash 复制代码
netstat -an | findstr 10101  # Windows

应该看到类似:

bash 复制代码
TCP    0.0.0.0:10101          0.0.0.0:0              LISTENING

允许端口通过防火墙

程序部署之后,在本机预览正常,但是其它机器无法访问,可能是端口被防火墙拦截了。

以管理员身份打开 PowerShell 或 CMD 执行命令:

bash 复制代码
New-NetFirewallRule -DisplayName "Allow Port 10101" -Direction Inbound -LocalPort 10101 -Protocol TCP -Action Allow
相关推荐
国思RDIF框架3 天前
RDIFramework.NET CS 敏捷开发框架 V6.3 版本重磅发布!.NET8+Framework双引擎,性能升级全维度进化
后端·.net
用户298698530144 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
赵榕5 天前
ClaimsPrincipal序列化为Json的正确姿势
.net
阿白的白日梦5 天前
winget基础管理---更新/修改源为国内源
windows
追逐时光者5 天前
一款使用 C# 编写专为 Windows 11 打造的文件资源管理器增强工具!
后端·.net
用户298698530148 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
牧马人win8 天前
SmartDapper.Repository
.net