You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用TopShelf将.NET Core 3.1 Web API部署为Windows服务?

将.NET Core 3.1 Web API 部署为 Windows 服务(借助TopShelf)

完全可以用TopShelf把你的.NET Core 3.1 Web API部署成Windows服务,TopShelf就是专门用来简化Windows服务的创建和部署流程的,对.NET Core项目适配性很好。

具体实现步骤

1. 安装TopShelf相关NuGet包

在你的Web API项目里安装两个包:TopShelf核心包和AspNetCore集成包,直接在NuGet包管理器搜索安装,或者用命令行:

Install-Package TopShelf
Install-Package TopShelf.AspNetCore

2. 修改Program.cs配置

把原来的WebAPI启动逻辑改成适配TopShelf的结构,示例代码如下:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Topshelf;
using Topshelf.AspNetCore;

namespace YourWebApiProject
{
    public class Program
    {
        public static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<WebHostService>(s =>
                {
                    s.ConstructUsing(_ => new WebHostService(CreateHostBuilder(args).Build()));
                    s.WhenStarted(service => service.Start());
                    s.WhenStopped(service => service.Stop());
                });

                // 配置服务的标识信息
                x.SetServiceName("YourWebApiService");
                x.SetDisplayName("你的Web API Windows服务");
                x.SetDescription("用TopShelf托管的.NET Core 3.1 Web API服务");

                // 设置服务运行身份,这里用LocalSystem,也可以根据需求改LocalService等
                x.RunAsLocalSystem();

                // 设置服务随系统自动启动
                x.StartAutomatically();
            });
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    // 删掉或注释掉原来的UseIISIntegration(),避免和TopShelf冲突
                });
    }
}

3. 发布项目

把项目发布成可执行文件,推荐用自包含部署模式,这样目标机器不用提前装.NET Core runtime。可以用Visual Studio的发布功能,或者命令行:

dotnet publish -c Release -r win-x64 --self-contained true

4. 安装和管理服务

打开管理员权限的命令提示符,进入发布后的输出目录,执行以下命令:

  • 安装服务:YourWebApiProject.exe install
  • 启动服务:YourWebApiProject.exe start
  • 停止服务:YourWebApiProject.exe stop
  • 卸载服务:YourWebApiProject.exe uninstall

注意事项

  • 一定要移除IIS相关配置,比如UseIISIntegration(),否则可能出现启动冲突
  • 如果WebAPI需要指定端口,在appsettings.json里配置Kestrel:
    "Kestrel": {
      "Endpoints": {
        "Http": {
          "Url": "http://localhost:5000"
        }
      }
    }
    
  • 服务运行的身份要具备访问项目资源的权限(比如数据库、本地文件等)

参考文档提示

TopShelf官方文档里有针对.NET Core项目的详细指引,包括服务配置、生命周期管理、权限设置等内容,你可以通过NuGet包对应的官方说明或者项目仓库的README获取细节。

内容的提问来源于stack exchange,提问作者useruser00

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:01:17