asp.net core web應用以windows服務的方式安裝運行



一、方案:使用Microsoft.Extensions.Hosting.WindowsServices實現;

1、在web項目中使用nuget安裝Microsoft.Extensions.Hosting.WindowsServices;

在這里插入圖片描述

2、在web應用的program.cs文件中,修改代碼如下:

代碼中將端口設置為了:2810;

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var host = Host.CreateDefaultBuilder(args);
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                host = host.UseWindowsService();
            }
            return host.ConfigureWebHostDefaults(webBuilder =>
            {
                var port=2810;//設置服務端口
                webBuilder.ConfigureKestrel(serverOptions =>
                {
                    serverOptions.Listen(IPAddress.Any, port);
                    serverOptions.Limits.MaxRequestBodySize = null;
                });
                webBuilder.UseStartup<Startup>();
            });
        }
    }

3、發布web項目:

在這里插入圖片描述

4、使用sc命令安裝服務

sc create app1 binpath= "D:\test\WebApplication1.exe" start= auto

命令中“app1”表示服務名稱,“binpath”表示web應用發布后的exe的路徑;“start”表示服務的啟動方式;

5、安裝成功后訪問127.0.0.1:2810

在這里插入圖片描述
成功!

二、參考

https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-3.0&tabs=visual-studio



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM