Asp.Net Core Web API .Net 6 WindowsService部署

背景

Asp.Net Core Web API 可以支持多种部署方式,如果服务器是Windows Server把项目部署在WindowsService中也是其中一个方式,可以支持随开机自动启动。

项目启动调整

在Asp.Ner Core Web API项目中引用包:Microsoft.Extensions.Hosting.WindowsServices

image

var options = new WebApplicationOptions
{
    Args = args,
    //这是因为从Windows Service中调用GetCurrentDirectory会返回C:\WINDOWS\system32
    ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
};

var builder = WebApplication.CreateBuilder(options);

image

//如果当前进程托管为Windows服务,则为True,否则为false
if (WindowsServiceHelpers.IsWindowsService())
{
    builder.Host.UseWindowsService();
}

新建配置文件:appsettings.Production.json
image

{
  "Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://localhost:5000"
      },
      "Https": {
        "Url": "http://localhost:5001"
      }
    }
  }
}

温馨提示: 使用了WindowsService部署,就不能使用Console类,否则会报错
image
如果需要做到兼容启动,请加上判断
image

服务常用命令

创建服务

New-Service -Name WebApplicationTest -BinaryPathName "路径\XX.exe" -Description "WebApplicationTest服务" -DisplayName "WebApplicationTest" -StartupType Automatic

{Name}:服务名称(如 WebApplicationTest)
{BinaryPathName}:应用程序的完整可执行文件路径(例如 C:\xx\xx.exe)。 请将可执行文件的文件名和扩展名包括在内
{Description}:服务说明(如 My sample service)
{DisplayName}:服务显示名称(如 My Service)
{StartupType}:启动类型(Automatic为自动)

启动服务: Start-Service -Name WebApplicationTest
查看服务: Get-Service -Name WebApplicationTest
暂停服务: Stop-Service -Name WebApplicationTest
移除服务: Remove-Service -Name WebApplicationTestsc.exe delete "WebApplicationTest"

posted @ 2022-07-01 11:51  零点-Angelo  阅读(1062)  评论(0编辑  收藏  举报