.net core web api 发布填坑

部署为 Windows 服务(最直接)

如果你的服务器是 Windows 系统,这是最推荐的方案。应用会像 SQL Server 一样在后台运行,开机自启、不会因误关控制台而中断

有种常用的实现方法:

  • 使用 Microsoft.Extensions.Hosting.WindowsServices 库(官方推荐)
    这是最优雅、最“.NET Core”的方式。只需在代码中做微小改动,就能让应用以Windows服务的方式运行

    1. 在项目的 Program.cs 中,为宿主构建器添加 .UseWindowsService() 扩展方法

    2. (关键步骤) 为避免服务运行时找不到文件,需要手动设置内容根目录

      csharp
      var options_args = new WebApplicationOptions
      {
          Args = args,
          ContentRootPath = WindowsServiceHelpers.IsWindowsService() 
                             ? AppContext.BaseDirectory 
                             : default
      };
      var builder = WebApplication.CreateBuilder(options_args);
      builder.Host.UseWindowsService(); 
      // ... 其余代码
    3. 发布应用后,使用管理员权限打开命令行,通过 sc create 命令创建服务

      # 1. 停止并删除旧服务
      sc stop 你的服务名
      sc delete 你的服务名
      
      # 2. 用正确的路径重新创建服务
      sc create 你的服务名 binPath= "D:\MyApp\publish\MyApp.exe" start= auto

      注释要去掉

    4. 然后发现部署成功了,但只能localhost访问,在项目根目录的 appsettings.json 文件中添加以下配置
      {
        "Kestrel": {
          "Endpoints": {
            "Http": {
              "Url": "http://*:5000"
            }
          }
        }
      }

      当然,防火墙要放开端口

posted @ 2026-06-26 16:08  石曼迪  Views(5)  Comments(0)    收藏  举报
瓴域建设-环保事业中心