在运行时检查托管服务器是IIS还是Kestrel在ASPNET Core中 [英] Check if hosting server is IIS or Kestrel at runtime in aspnet core

查看:405
本文介绍了在运行时检查托管服务器是IIS还是Kestrel在ASPNET Core中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在Kestrel(本地)或IIS InProcess(生产)下运行我的应用程序。

I'm currently running my application under either Kestrel (locally) or IIS InProcess (production).

return WebHost.CreateDefaultBuilder(args)
    .ConfigureKestrel(options => options.AddServerHeader = false)
    .UseIIS()
    .UseStartup<Startup>();

我希望能够在运行时在控制器中获取托管服务器的名称,这样我就可以实现以下目标:

I'd like to be able to get the hosting server name at runtime in a controller so I can achieve the following:

if (hostingServer == "kestrel")
{
    DoSomething();
}
else
{
    DoSomethingElse();
}

在这种情况下,可以避免使用非ASCII字符Kestrel的响应标头中不支持。理想情况下,我会删除non-ascii标头,但目前它是旧版互操作性所必需的。

In this specific case it's to get around the fact that non-ascii characters are not supported in response headers with Kestrel. Ideally I would remove the non-ascii header but currently it's required for legacy interoperability.

任何帮助将不胜感激。

推荐答案

即使我使用InProcess在IIS中托管它,它也仍然是 dotnet 进程(我的猜测是,您需要获取父进程才能获取w3wp进程)。

Checking for process name didn't work for me, even when hosting in IIS with InProcess it still proxies to the dotnet process (my guess is that you would need to get parent process to get the w3wp process).

内部.NET Core调用 IsAspNetCoreModuleLoaded() NativeMethods.cs ,可以在 WebHostBuilderIISExtensions.cs 。因此,可以使用以下代码检查IIS。

Internally .NET Core calls IsAspNetCoreModuleLoaded() in NativeMethods.cs as can be found in WebHostBuilderIISExtensions.cs. So checking for IIS can be done with the following code.

internal static class NativeMethods
{
    internal const string AspNetCoreModuleDll = "aspnetcorev2_inprocess.dll";

    [DllImport("kernel32.dll")]
    private static extern IntPtr GetModuleHandle(string lpModuleName);

    public static bool IsAspNetCoreModuleLoaded()
    {
        return GetModuleHandle(AspNetCoreModuleDll) != IntPtr.Zero;
    }
}

这篇关于在运行时检查托管服务器是IIS还是Kestrel在ASPNET Core中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆