告别IIS依赖!ASP.NET Core如何通过Windows Service实现服务托管

文章目录

背景

IIS默认会定时回收进程,这会严重影响后台应用的定时任务,接收消息队列等需要不间断运行的功能。

步骤

添加Nuget

添加Microsoft.Extensions.Hosting.WindowsServices

powershell 复制代码
NuGet\Install-Package Microsoft.Extensions.Hosting.WindowsServices

修改builder

在Program.cs里修改builder创建方式,将应用路径设为项目启动路径

csharp 复制代码
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    ContentRootPath = AppContext.BaseDirectory, // 强制绑定到发布目录
    Args = args
});

添加Windows Service

csharp 复制代码
builder.Services.AddWindowsService(options =>
{
    options.ServiceName = "ASP.Net 10 Serivce";
});

发布

发布选择目标运行时为 win-x64

bash 复制代码
dotnet publish -c Release -r win-x64 --self-contained false -o ./publish

添加到Services

通过启动参数指定启动端口

bash 复制代码
sc create "MyASPNetCoreService" binPath= "C:\MyApp\MyAspNetCoreApp.exe --urls=http://0.0.0.0:5001" start=delayed-auto
  • 删除服务
bash 复制代码
sc delete "MyASPNetCoreService"
  • 开机自动启动
  • 尝试重启服务
相关推荐
love530love1 天前
OpenClaw Windows Companion 桌面客户端 连接 LM Studio 完整配置指南
人工智能·windows·python·openclaw
码兄科技1 天前
实战:基于Spring Boot + UniApp的地理信息小程序开发
spring boot·后端·uni-app
腾讯云云开发1 天前
腾讯云 CloudBase 登上 WAIC:我们为 Agent 重新设计了云的生产线
后端
星栈1 天前
从装一堆工具到看懂 Node 工程化思维:我的项目复盘记录
后端·node.js
65岁退休Coder1 天前
LangChain v1.3.4 笔记 - 05 Agent 上下文记忆
后端
颜酱1 天前
04 | 召回前置准备:搭好召回所需的四个数据库
前端·人工智能·后端
JaneConan1 天前
鸿蒙 韶非 UI 系列:能力调用 startAbilityForResult,跳能力拿回参,鸿蒙能力路由入门
后端·harmonyos
晴空了无痕1 天前
从 Go 基础到 K8s:一条可落地的 Go 服务端成长路线
开发语言·后端·golang·kubernetes
用户8356290780511 天前
如何使用 Python 在 Excel 中添加、编辑和删除超链接
后端·python
花椒技术1 天前
原本要 2 天的服务端冒烟前置审查,为什么 3 分半就能出报告?|QA 质量交付实践(三)
后端·ai编程·测试