2017-02-16 92 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 - 它將顯示有關配置的命令行開關的信息,因此可以很容易地選擇正確的值。

相關問題