• .NET 6学习笔记(3)——在Windows Service中托管ASP.NET Core并指定端口


    在上一篇《.NET 6学习笔记(2)——通过Worker Service创建Windows Service》中,我们讨论了.NET Core 3.1或更新版本如何创建Windows Service。本篇我们将在此基础上,托管ASP.NET Core程序并指定端口。
    首先让我们创建一个ASP.NET Core Web App,当然Web Api类型也是可以的。通过NuGet来安装Microsoft.Extensions.Hosting.WindowsServices。该库提供了必要的UseWindowsSrvice方法。

    让我们对Program.cs文件稍作修改。在InWindowsSerivice的状态下,将ContentRootPath设置为AppContext.BaseDirectory。这是因为从Windows Service中调用GetCurrentDirectory会返回C:\WINDOWS\system32,所以某软需要我们将ContentRootPath指定到WebApp的exe所在目录。还有不要忘了在builder的Host属性上调用UseWindowsService方法。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    UseWindowsService方法。
    using Microsoft.Extensions.Hosting.WindowsServices;
     
    var options = new WebApplicationOptions
    {
        Args = args,
        ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
    };
     
    var builder = WebApplication.CreateBuilder(options);
     
    // Add services to the container.
    builder.Services.AddRazorPages();
     
    builder.Host.UseWindowsService();
     
    var app = builder.Build();

    完成上述步骤之后,我们已经可以通过PowerShell来创建Windows Service了。但是默认情况下ASP.NET Core被绑定到http://localhost:5000。这可能不符合我们的期望。那如何修改呢?比较简单的方式是增加appsettings.Production.json文件,添加仅针对发布后程序的配置。好处是不会影响Visual Studio中的Debug,如果我们在代码中通过UseUrls方法,或者修改launchSettings.json文件,会导致Debug时不会自动启动WebBrowser的奇怪问题。

    本篇我们讨论了如何在Windows Service托管ASP.NET Core程序并指定端口。水平有限,还请各位大佬扶正。

    Github:
    manupstairs/WebAppHostOnWinService (github.com)
    Gitee:
    manupstairs/WebAppHostOnWinService (gitee.com)

     

  • 相关阅读:
    PIMPL技巧
    如何对齐MathType公式和Word文字排版
    AFL源码分析(一)
    里氏代换原则
    5.区块链系列之私钥管理
    java语言概述
    Linux:进度条(小程序)以及git三板斧
    Oracle(15)Managing Users
    MySQL : 彻底搞懂一条SQL的执行过程
    数位DP
  • 原文地址:https://www.cnblogs.com/manupstairs/p/16083616.html