ASP.NET Core Windows服务托管:RunAsService与Run、NSSM选型咨询
Hey there, let me break down your ASP.NET Core Windows hosting options based on what you've shared and the official guidance:
What the Official Docs Say
在Windows上不使用IIS托管ASP.NET Core应用的推荐方式是将其作为Windows服务运行,文档示例要求使用RunAsService()启动WebHost。
Your Current Setup
- You're currently using the
Run()method to launch your ASP.NET Core application - Your Linux deployment is already locked in with Nginx + systemd service—nice work getting that sorted!
- Before diving into the docs, you were planning to replicate a similar Nginx-based setup on Windows
Your Two Main Options for Windows Hosting
Option 1: Go with the Official Recommendation (Windows Service via RunAsService())
This is Microsoft's preferred approach for hosting ASP.NET Core on Windows without IIS, and for good reason:
- To make the switch from
Run()toRunAsService(), here's what you'll need to do:- Add the
Microsoft.Extensions.Hosting.WindowsServicesNuGet package to your project - Update your host configuration to call
UseWindowsService()beforeRunAsService()(for older WebHost setups) — if you're on .NET 6+ with the minimal model, just useHost.CreateDefaultBuilder().UseWindowsService()andRun()will handle the service behavior automatically - Install your app as a native Windows service using PowerShell's
New-Servicecommand or thesc createutility
- Add the
- Perks: Native Windows service management (auto-start on system boot, built-in recovery policies, seamless logging to Event Viewer)
Option 2: Stick with Nginx on Windows (For Cross-OS Consistency)
While it's not the official recommendation, running Nginx as a reverse proxy on Windows alongside your app is totally doable if you want to keep your deployment pattern consistent across Linux and Windows:
- You can keep using
Run()for your app, but you'll need a way to run it as a service (sinceRun()alone just starts a console process) - Here's how to set it up:
- Install Nginx on Windows and configure it to proxy requests to your app's listening port
- Use a tool like NSSM (Non-Sucking Service Manager) to wrap your ASP.NET Core console app into a Windows service — this lets Windows manage it like any other service (auto-start, etc.)
- Pros: Same reverse proxy layer (Nginx) handling SSL, load balancing, and static assets across both OSes; no big code changes to your app
- Cons: Adds an extra third-party tool (NSSM) to your setup; you lose the native Windows service integration that
RunAsService()provides out of the box
Quick Version Check
If you're on .NET 6 or later with the minimal hosting model (the top-level statements approach), the service integration is even smoother. You don't need to call RunAsService() explicitly — just add UseWindowsService() to your host builder, and when you install the app as a service, it will run correctly without changing your Run() call.
内容的提问来源于stack exchange,提问作者Carl Quirion

