在上一篇《.NET 6學習筆記(2)——通過Worker Service創建Windows Service》中,我們討論了.NET Core 3.1或更新版本如何創建Windows Service。本篇我們將在此基礎上,托管ASP.NET Core程序並指定端口。
首先讓我們創建一個ASP.NET Core Web App,當然Web Api類型也是可以的。通過NuGet來安裝Microsoft.Extensions.Hosting.WindowsServices。該庫提供了必要的UseWindowsSrvice方法。
讓我們對Program.cs文件稍作修改。在InWindowsSerivice的狀態下,將ContentRootPath設置為AppContext.BaseDirectory。這是因為從Windows Service中調用GetCurrentDirectory會返回C:\WINDOWS\system32,所以某軟需要我們將ContentRootPath指定到WebApp的exe所在目錄。還有不要忘了在builder的Host屬性上調用UseWindowsService方法。
UseWindowsService方法。 using Microsoft.Extensions.Hosting.WindowsServices; var options = new WebApplicationOptions { Args = args, ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default }; var builder = WebApplication.CreateBuilder(options); // Add services to the container. builder.Services.AddRazorPages(); builder.Host.UseWindowsService(); var app = builder.Build();
完成上述步驟之后,我們已經可以通過PowerShell來創建Windows Service了。但是默認情況下ASP.NET Core被綁定到http://localhost:5000。這可能不符合我們的期望。那如何修改呢?比較簡單的方式是增加appsettings.Production.json文件,添加僅針對發布后程序的配置。好處是不會影響Visual Studio中的Debug,如果我們在代碼中通過UseUrls方法,或者修改launchSettings.json文件,會導致Debug時不會自動啟動WebBrowser的奇怪問題。
本篇我們討論了如何在Windows Service托管ASP.NET Core程序並指定端口。水平有限,還請各位大佬扶正。
Github:
manupstairs/WebAppHostOnWinService (github.com)
Gitee:
manupstairs/WebAppHostOnWinService (gitee.com)