2017-02-16 87 views

回答

0

我相信没有直接的方法来实现这种开箱即用的功能。至少我没有找到一个。正如我所知道的,事实上,ASP.NET Core应用程序实际上是一个独立的应用程序,对它的父上下文一无所知,除非后者会显示有关它自己的信息。

例如在配置文件中,我们可以知道我们正在运行的是哪种安装类型:productiondevelopment。我们可以假设productionIIS,而development不是。但是,这并没有为我工作。由于我的生产设置可能是IISwindows service

所以我已经通过向我的应用程序提供不同的命令行参数来解决此问题,具体取决于它应该执行的运行类型。实际上,这对我来说很自然,因为windows service确实需要不同的方法来运行。

例如在我的情况的代码看起来有点像这样:

namespace AspNetCore.Web.App 
{ 
    using McMaster.Extensions.CommandLineUtils; 
    using Microsoft.AspNetCore; 
    using Microsoft.AspNetCore.Hosting; 
    using Microsoft.AspNetCore.Hosting.WindowsServices; 
    using System; 
    using System.Diagnostics; 
    using System.IO; 

    public class Program 
    { 
     #region Public Methods 

     public static IWebHostBuilder GetHostBuilder(string[] args, int port) => 
      WebHost.CreateDefaultBuilder(args) 
       .UseKestrel() 
       .UseIISIntegration() 
       .UseUrls($"http://*:{port}") 
       .UseStartup<Startup>(); 

     public static void Main(string[] args) 
     { 
      var app = new CommandLineApplication(); 

      app.HelpOption(); 
      var optionHosting = app.Option("--hosting <TYPE>", "Type of the hosting used. Valid options: `service` and `console`, `console` is the default one", CommandOptionType.SingleValue); 
      var optionPort = app.Option("--port <NUMBER>", "Post will be used, `5000` is the default one", CommandOptionType.SingleValue); 

      app.OnExecute(() => 
      { 
       // 
       var hosting = optionHosting.HasValue() 
        ? optionHosting.Value() 
        : "console"; 

       var port = optionPort.HasValue() 
        ? new Func<int>(() => 
        { 
         if (int.TryParse(optionPort.Value(), out var number)) 
         { 
          // Returning successfully parsed number 
          return number; 
         } 

         // Returning default port number in case of failure 
         return 5000; 
        })() 
        : 5000; 

       var builder = GetHostBuilder(args, port); 

       if (Debugger.IsAttached || hosting.ToLowerInvariant() != "service") 
       { 
        builder 
         .UseContentRoot(Directory.GetCurrentDirectory()) 
         .Build() 
         .Run(); 
       } 
       else 
       { 
        builder 
         .UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)) 
         .Build() 
         .RunAsService(); 
       } 
      }); 

      app.Execute(args); 
     } 

     #endregion Public Methods 
    } 
} 

此代码不仅允许选择类型的主机(serviceconsole - 该选项IIS应该使用),也允许当您作为Windows服务运行时,更改端口是非常重要的。

另一件好事是使用参数解析库,McMaster.Extensions.CommandLineUtils - 它将显示有关配置的命令行开关的信息,因此可以很容易地选择正确的值。

相关问题