ASP.Net Core Web 6 部署成Windows服务
安装Neget包
Install-Package Microsoft.Extensions.Hosting.WindowsServices
编码
Program.cs
代码如下
using Microsoft.Extensions.Hosting.WindowsServices;
var options = new WebApplicationOptions
{
Args = args,
ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
};
var builder = WebApplication.CreateBuilder(options);
var configuration = builder.Configuration;
builder.Host.UseWindowsService();
builder.WebHost.ConfigureKestrel(options =>
{
//Http端口
options.ListenAnyIP(configuration.GetSection("Host:HttpPort").Get<int>());
//Https端口
options.ListenAnyIP(configuration.GetSection("Host:HttpsPort").Get<int>(), listenOptions => listenOptions.UseHttps());
});
// Add services to the container.
var app = builder.Build();
// Configure the HTTP request pipeline.
app.Run();
部署
程序编译发布后可以使用cmd
的sc
命令部署成Windows服务
----------------------安装----------------------
set serviceName=TestTask
set serviceFilePath="F:\WebApplication.exe"
set serviceDescription="测试任务"
sc create %serviceName% BinPath=%serviceFilePath%
sc config %serviceName% start=auto
sc config %serviceName% start=delayed-auto
sc description %serviceName% %serviceDescription%
sc failure %serviceName% reset= 0 actions= restart/1200000
sc start %serviceName%
pause
----------------------卸载----------------------
set serviceName=TestTask
sc stop %serviceName%
sc delete %serviceName%
pause