Jam*_*urt 10 c# asp.net-core .net-6.0
我的目标是以最简单的方式将 ASP.NET Core 6 应用程序作为 Windows 服务运行,我理解为使用下面所示的代码。
我已经包含了这两行(尽管只有顶部是必要的):
using Microsoft.AspNetCore.Hosting.WindowsServices;
using Microsoft.Extensions.Hosting.WindowsServices;
Run Code Online (Sandbox Code Playgroud)
并安装 nuget 软件包:
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="6.0.0" />
Run Code Online (Sandbox Code Playgroud)
.UseWindowsService()但使用以下代码时无法解析IWebHostBuilder:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseConfiguration(Configuration)
.ConfigureServices(ConfigureServices)
.UseUrls(Configuration.GetBindHostUrl())
.UseStartup<Startup>()
.UseWindowsService(); // not found
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
“IWebHostBuilder”不包含“UseWindowsService”的定义,并且最佳扩展方法重载“WindowsServiceLifetimeHostBuilderExtensions.UseWindowsService(IHostBuilder)”需要“IHostBuilder”类型的接收器
我在这里缺少什么?
您可以尝试使用更通用的IHostBuilder而不是使用 WebHost :
var host = Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseSystemd()
.ConfigureWebHostDefaults(webbuilder =>
{
//Configure here your WebHost. For example Startup;
webbuilder.UseStartup<Startup>();
});
Run Code Online (Sandbox Code Playgroud)
编辑:
从评论中移出,因为很多人发现它很有用,并提高评论的可见性:
要使用该UseWindowsService()方法,您需要安装WindowsServices NuGet-Package。在某些情况下,它可以在没有 NuGet-Package 的情况下构建,但无法运行!
我刚刚从 .net 3 迁移到最新的 7.0,将 VS2019 迁移到 2022,然后必须从 NuGet 包管理器安装依赖项:
然后我就可以在任何 Windows 或 Linux 版本上运行。
作为参考,要创建 Windows 服务,只需以管理员身份运行批处理:
安装.cmd
chcp 1252>NUL
SET mypath=%~dp0
sc create "service.name" displayname= "display.name" binpath= %mypath:~0,-1%\app-name.exe start= auto
sc description "service.name" "service description"
NET START service.name
pause
Run Code Online (Sandbox Code Playgroud)
卸载.cmd
NET STOP service.name
sc delete "service.name"
pause
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13438 次 |
| 最近记录: |