windows 服務中託管asp.net core

wzh0717發表於2018-08-23

在windows 服務中託管asp.net core

SDK 2.1.300

官方示例

1、新增執行識別符號
xml <PropertyGroup> <TargetFramework>netcoreapp2.1</TargetFramework> <RuntimeIdentifier>win7-x64</RuntimeIdentifier> </PropertyGroup>
2、新增包引用 dotnet add package Microsoft.AspNetCore.Hosting.WindowsServices -v 2.1.0 -s https://www.nuget.org/api/v3

dotnet命令

包源

3、確認匯入是否成功
xml <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.App" /> <PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="2.1.0" /> </ItemGroup>
4、修改Program Main 函式

 public static void Main(string[] args)
{
     CreateWebHostBuilder(args).Build().RunAsService();
 }

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
 {
    var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
    var pathToContentRoot = Path.GetDirectoryName(pathToExe);
    return WebHost.CreateDefaultBuilder(args)
            .UseKestrel()
            .UseUrls("http://*:5001", "http://*:5002")
            .ConfigureAppConfiguration((context, config) =>
            {
                // Configure the app here.
            })
            .UseContentRoot(pathToContentRoot)
            .UseStartup<Startup>();
    }

5、釋出執行

dotnet publish -c Release -o "F:winservicesmvcApp21"

6、使用sc.exe工具建立服務 此處使用系統原始DOS命令

釋出根目錄下:sc create mvcApp21 binPath= "F:winservicesmvcApp21mvcApp21.exe"

確保 binPath= 引數與其值之間存在空格

啟動服務 sc start MyService
檢視服務狀態 sc query MyService
停止服務 sc stop MyService
刪除服務 sc delete MyService

7、可能遇到的問題

8、.net core 部署服務其他方案

使用NSSM把.Net Core部署至Windows 服務

9、回顧.net 部署服務

使用Topshelf建立Windows 服務

wcf服務

相關文章