文章目录
- 1.添加NuGet包:
- 2.修改Program.cs:
- 3.发布应用程序
- [4.安装与管理 Windows 服务](#4.安装与管理 Windows 服务)
- [指定Web API监听端口,2种方式](#指定Web API监听端口,2种方式)
-
- [第一种方式,在程序的 `appsettings.json` 配置文件中配置:](#第一种方式,在程序的
appsettings.json配置文件中配置:) - 第二种方式,在启动程序时用命令行启动参数指定端口:
- 验证配置:
- [第一种方式,在程序的 `appsettings.json` 配置文件中配置:](#第一种方式,在程序的
- 允许端口通过防火墙
有时候会有将.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