【问题标题】:Check if Asp.Net(Core) application is hosted in IIS检查 Asp.Net(Core) 应用程序是否托管在 IIS 中
【发布时间】:2020-10-09 18:02:59
【问题描述】:

如何检查应用程序是否托管在 IIS 中?

【问题讨论】:

    标签: asp.net iis


    【解决方案1】:

    检查环境变量APP_POOL_ID是否设置。

    public static bool InsideIIS() =>
        System.Environment.GetEnvironmentVariable("APP_POOL_ID") is string;
    

    All of environment variables that iis sets on a child process

    【讨论】:

    • 自 Asp.Net Core 6 以来,“APP_POOL_ID”变量似乎不再可用。我现在使用“ASPNETCORE_IIS_PHYSICAL_PATH”环境变量作为替代。
    【解决方案2】:

    我试过 Branimir Ričko 的回答,但发现不正确:在 IIS express 下运行时也设置了此环境变量。

    所以这是我的修改版本:

    static bool IsRunningInsideIIS() =>
        System.Environment.GetEnvironmentVariable("ASPNETCORE_HOSTINGSTARTUPASSEMBLIES") is string startupAssemblies &&  
     startupAssemblies.Contains(typeof(Microsoft.AspNetCore.Server.IISIntegration.IISDefaults).Namespace);
    

    【讨论】:

      【解决方案3】:

      我相信没有直接的方法可以开箱即用地实现这一目标。至少我还没有找到。原因,据我所知,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
          }
      }
      

      此代码不仅允许选择主机类型(serviceconsoleIIS 应该使用的选项),还允许更改端口,当您以 Windows 运行时,这很重要服务。

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

      【讨论】:

      • 请问,当我执行 RunAsService 时,应用程序不会执行...我必须创建一个 worker 吗?
      猜你喜欢
      • 1970-01-01
      • 2015-07-29
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多