.NET 5學習筆記(11)—— Host Blazor WebAssembly in a Windows Service

實在是被某軟忽悠瘸了,憤而寫此一篇。但願能讓一樣需求的同窗們少走彎路。
某軟在《在 Windows 服務中託管 ASP.NET Core》中,介紹了經過建立Worker Service工程,來將.NET Core和.NET 5的程序以Windows Service的形式運行。可是某軟你得說明,託管ASP.NET Core Web Application,並不須要額外建立一個Worker Service工程啊,再加上GitHub上兩個放在一塊的sample project,直接把我誤導瘸了……
今天我就要記錄一下這個事情,實際上是多麼的簡單,控訴某軟文檔不走心。
接下來讓咱們實踐一把。根據劇情須要,這裏應該是一個Blazor WebAssembly App。git

記得勾選ASP.NET Core hosted,會爲咱們額外建立一個用於Host的ASP.NET Core Web Application。若是不新建Web Application,同時也沒有可用的Web Application,單一的Blazor WebAssembly App是沒有辦法使用Windows Service託管的。github

Create按鈕點擊下去,只見Visual Studio一通操做,建了三個工程。咱們穩住不要慌,按F5運行,如今的狀況是下圖這個樣子。左邊是咱們新建的Blazor App在瀏覽器裏跑起來的樣子。右側的Solution Explorer中,BlazorHostInWinService.Client是程序的主體,全部的Page都在這裏畫。BlazorHostInWinService.Server是一個簡單的WebApi工程,其中的WeatherForecastController提供了給Blazor Fetch Data頁面測試用的天氣數據。至於最下面的Shared工程,能夠理解爲Client和Server之間傳遞數據,共享所使用的DTO對象,在該示例中,僅有一個Class WeatherForecast。web

當前咱們的程序是經過IIS Express來運行的,接着咱們要把該工程經過Windows Service來託管運行。首先須要給BlazorHostInWinService.Server工程添加NuGet包 Microsoft.AspNetCore.Hosting.WindowsServices。再打開Program.cs文件,爲IHostBuilder對象添加對UseWindowsService方法的調用。windows

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseWindowsService()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

額,好像也沒有其餘事情能夠作了,讓咱們publish該項目。依然是選擇BlazorHostInWindowsService.Server工程,右鍵菜單中的publish點擊後,出現以下界面,選擇Folder後點擊Finish。瀏覽器

在以下圖的界面中,再一次開心的點擊publish。編譯過程當中咱們能夠摸會魚,直到在Output窗口中出現迷人的信息:
========== Build: 3 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
========== Publish: 1 succeeded, 0 failed, 0 skipped ==========visual-studio

而後讓咱們打開Target location,即bin\Release\net5.0\publish\。把全部的文件都拷貝到咱們但願部署的位置,好比C:\Users\xingzheng\Documents\BlazorWinService文件夾。
最後就是建立Windows Service了,咱們打開具備admin權限的CMD窗口。鍵入測試

sc create FirstBlazorAppService binPath="C:\Users\dell\Documents\BlazorWinService\BlazorInWinServiceTest1.Server.exe"

此時咱們打開Windows Services的界面,啓動FirstBlazorAppService便可。再返回到瀏覽器輸入http://localhost:5000ui

標題是我在Index.razor文件中手動改的,也爲了區別以前經過IIS Express運行的頁面。
本篇就到這裏,簡單地介紹瞭如何將Blazor App經過Windows Service託管。
GitHub:
https://github.com/manupstairs/BlazorHostInWinServicespa

相關文章
相關標籤/搜索