.net core web api 发布填坑
部署为 Windows 服务(最直接)
如果你的服务器是 Windows 系统,这是最推荐的方案。应用会像 SQL Server 一样在后台运行,开机自启、不会因误关控制台而中断。
有种常用的实现方法:
-
使用
Microsoft.Extensions.Hosting.WindowsServices库(官方推荐):
这是最优雅、最“.NET Core”的方式。只需在代码中做微小改动,就能让应用以Windows服务的方式运行。-
在项目的
Program.cs中,为宿主构建器添加.UseWindowsService()扩展方法。 -
(关键步骤) 为避免服务运行时找不到文件,需要手动设置内容根目录:
var options_args = new WebApplicationOptions { Args = args, ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default }; var builder = WebApplication.CreateBuilder(options_args); builder.Host.UseWindowsService(); // ... 其余代码 -
发布应用后,使用管理员权限打开命令行,通过
sc create命令创建服务# 1. 停止并删除旧服务 sc stop 你的服务名 sc delete 你的服务名 # 2. 用正确的路径重新创建服务 sc create 你的服务名 binPath= "D:\MyApp\publish\MyApp.exe" start= auto
注释要去掉
- 然后发现部署成功了,但只能localhost访问,在项目根目录的
appsettings.json文件中添加以下配置{ "Kestrel": { "Endpoints": { "Http": { "Url": "http://*:5000" } } } }
当然,防火墙要放开端口
-

浙公网安备 33010602011771号