ASP.NET Core項目基於Windows 服務的打包託管

1. 工程創建

工程目標框架可爲 .NetFramework 或 .NetCore,模板爲 .NetCore下的API工程,正常編寫工程代碼即可

2.轉換項目爲Windows服務

  1. 修改工程的 .csproj 文件,添加Windows 運行時標識符
<PropertyGroup>
   <TargetFramework>net461</TargetFramework>
   <RuntimeIdentifier>win-x64</RuntimeIdentifier>
 </PropertyGroup>
  1. 添加Microsoft.AspNetCore.Hosting.WindowsServices 引用包
  2. 修改 Program.cs 文件
   public class Program
   {
       public static void Main(string[] args)
       {
           // 1.修改爲調用 RunAsService()
           CreateWebHostBuilder(args).Build().RunAsService();
       }

       public static IWebHostBuilder CreateWebHostBuilder(string[] args)
       {
           // 2.調用 UseContentRoot 並使用應用的發佈位置路徑
           var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
           var pathToContentRoot = Path.GetDirectoryName(pathToExe);

           return WebHost.CreateDefaultBuilder(args)
               .ConfigureAppConfiguration((context, config) =>
               {
                    // Configure the app here.
               })
               .UseContentRoot(pathToContentRoot)
               .UseStartup<Startup>();
       }
   }

3. 發佈工程

可用VS內嵌發佈插件發佈,格式爲“文件系統”,或者使用命令行發佈,在解決方案文件夾下執行命令(運行時根據工程而定):
dotnet publish --configuration Release --runtime win-x64

4. sc命令工具打包服務(管理員身份執行)

  1. 創建服務:
    在打包後的文件夾下執行命令:
    sc create MyServiceName.exe binPath= "MyServiceName.exe path"
    注意:binPath 值是應用的可執行文件的路徑,其中包括可執行文件的文件名。 等於號和路徑開頭的引號字符之間需要添加空格。

  2. 啓動服務
    sc start MyServiceName.exe
    服務啓動成功後,若是Web 應用時,在應用所在路徑中瀏覽應用,默認路徑 http://localhost:5000

  3. 停止服務
    sc stop MyServiceName.exe

  4. 卸載服務
    sc delete MyServiceName.exe

END
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章