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

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

问题描述

我目前正在 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();
}

在这种特定情况下,它是为了避免在 Kestrel 的响应标头中不支持非 ascii 字符这一事实.理想情况下,我会删除非 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;
    }
}

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

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