如何将参数从承载它的WIndows服务传递到ASP .NET Core应用程序

时间:2018-09-10 09:50:40

标签: c# windows-services asp.net-core-webapi asp.net-core-2.1

我按照本指南https://docs.microsoft.com/en-gb/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-2.1

创建了Windows服务中托管的ASP .NET Core 2.1应用程序。

启动Windows服务时,我以编程方式将IP端口作为参数传递,因为我想将使​​用的applicationUrl更改为launchsettings.json。

下面,我报告启动服务的代码

ServiceController controller = ...;
// Do something
args = new string[]{8080};
controller.Start(args);

在我的ASP .Net Core项目中,我有一个CustomWebHostService类,在该类中可以在OnStarting()方法中获取上一个参数。

public class CustomWebHostService : WebHostService
{
    ////private Microsoft.Extensions.Logging.ILogger _logger;

    /// <summary>
    /// The <see cref="Logger"/> object
    /// </summary>
    private static Logger _logger;

    public CustomWebHostService(IWebHost host) : base(host)
    {
        ////_logger = host.Services.GetRequiredService<ILogger<CustomWebHostService>>();

        _logger = LogManager.GetCurrentClassLogger();
    }

    protected override void OnStarting(string[] args)
    {
        ////_logger.LogDebug("OnStarting method called.");
        _logger.Info("OnStarting method called.");

        // TODO Change launchsettings with the IP Port


        base.OnStarting(args);
    }

    protected override void OnStarted()
    {
        ////_logger.LogDebug("OnStarted method called.");
        _logger.Info("OnStarted method called.");

        base.OnStarted();
    }

    protected override void OnStopping()
    {
        ////_logger.LogDebug("OnStopping method called.");
        _logger.Info("OnStopping method called.");

        base.OnStopping();
    }
}

现在,我应该将此参数传递给构建器(IWebHostBuilder接口)并更新我的配置。

builder.UseUrls(String.Format("http://*:{0};http://localhost:{0}", myPort));

我该怎么办?

谢谢。

0 个答案:

没有答案