c# - 在 aspnet core 运行时检查托管服务器是 IIS 还是 Kestrel

标签 c# iis asp.net-core .net-core kestrel-http-server

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

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

我希望能够在运行时在 Controller 中获取托管服务器名称,以便实现以下目标:

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

在这种特定情况下,它是为了解决这样一个事实,即 Kestrel 的响应 header 不支持非 ascii 字符。理想情况下,我会删除非 ascii header ,但目前它是遗留互操作性所必需的。

如有任何帮助,我们将不胜感激。

最佳答案

最简单的方法可能是阅读 System.Diagnostics.Process.GetCurrentProcess().ProcessName。如果它是 w3wpiisexpress 你知道主机是 IIS/IIS Express,而 dotnet (或其他名称,当你使用独立部署时) 表示红隼。这仅适用于进程中的部署。如果您不在流程中,这将不起作用。在 https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/aspnet-core-module 了解更多信息

例子:

/// <summary>
/// Check if this process is running on Windows in an in process instance in IIS
/// </summary>
/// <returns>True if Windows and in an in process instance on IIS, false otherwise</returns>
public static bool IsRunningInProcessIIS()
{
    if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
    {
        return false;
    }

    string processName = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().ProcessName);
    return (processName.Contains("w3wp", StringComparison.OrdinalIgnoreCase) ||
        processName.Contains("iisexpress", StringComparison.OrdinalIgnoreCase));
}

关于c# - 在 aspnet core 运行时检查托管服务器是 IIS 还是 Kestrel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55852820/

相关文章:

c# - 本地化文件无法有效地在 MVC ASP.NET Core 2.2 中呈现 Razor 页面

c# - 强制 Etag 检查 Blob 创建

c# - 用于独立 Windows 应用程序的 csharp 平面文件数据库

c# - double 型属性(类)和 double 型字段(SQL 查询)中 float 表示的差异

c# - 在 IIS 上发布时出现 EmguCV 异常

.net - IIS 托管 -> 非托管 -> 托管 -> StackOverflowException

c# - NLog .NET Core aspnet-user-identity 始终为空

asp.net-core - 在 .Net Core 2.2 中将 HttpResponseMessage 作为 IActionResult 返回的正确方法

c# - 静态对象的非静态方法的参数是否会被多个线程共享?

iis - 使用 HttpPlatformHandler 托管在 IIS 上的 Suave 应用程序关闭连接