1. 程式人生 > 其它 >AspNet Core 部署為Windows服務

AspNet Core 部署為Windows服務

目錄

https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-3.0&tabs=visual-studio

部署看網站的性質
對於使用 Razor Pages 或 MVC 框架的基於 Web 應用的服務,請在專案檔案中指定 Web SDK:

<Project Sdk="Microsoft.NET.Sdk.Web">

如果服務僅執行後臺任務(例如 託管服務),請在專案檔案中指定輔助角色 SDK:

<Project Sdk="Microsoft.NET.Sdk.Worker">

基於 Web 應用的服務

建立 AspNet Core 專案,專案名稱為:WebWinServer
新增包

<Project Sdk="Microsoft.NET.Sdk.Web">
  ...
  <ItemGroup>
    ...
    <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="3.1.13" />
  </ItemGroup>

</Project>

接著修改 Program.cs

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseWindowsService()//指定專案可以部署為Windows服務
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                        .UseUrls("http://*:8787"); //使用的埠號
                });

指令碼

參見:https://github.com/dotnet/AspNetCore.Docs/tree/main/aspnetcore/host-and-deploy/windows-service/samples/scripts

安裝為服務並執行.bat

set name=WebWinServer
net stop %name%
sc delete %name%
sc create %name% binPath= %cd%\WebWinServer.exe  start= auto
net start  %name%
Pause

停止並解除安裝服務.bat

set name=MQTTBroker
net stop %name%
sc delete %name%
Pause

服務僅執行後臺任務

建立控制檯程式,專案名稱為:WorkerWinService,修改專案工程檔案為:

<Project Sdk="Microsoft.NET.Sdk.Worker"> 

新增包 Microsoft.AspNetCore.Hosting.WindowsServices

<Project Sdk="Microsoft.NET.Sdk.Worker"> 
  ...
  <ItemGroup>
     ...
    <PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.1.13" />
  </ItemGroup>
</Project>

接著修改 Program.cs

       public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>(); /指定專案可以部署為Windows服務
                });

定義後臺Worker, 繼承 BackgroundService
Worker.cs

    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);
            }
        }
    }

指令碼

安裝和解除安裝指令碼同上,只是修改服務名稱為 WorkerWinService 即可。

依賴部署 VS 獨立部署

參見:https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-3.0&tabs=visual-studio