实在是被某软忽悠瘸了,愤而写此一篇。但愿能让一样需求的同窗们少走弯路。
某软在《在 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