Check if hosting server is IIS or Kestrel at runtime in aspnet core

北城余情 提交于 2020-01-01 09:33:29

问题


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();
}

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.

Any help would be massively appreciated.


回答1:


When the application starts the hosting method can be exposed in IApplicationBuilder.ServerFeatures. Through here you can find items that reference Kestrel vs reverse proxy configuration.

The IApplicationBuilder available in the Startup.Configure method exposes the ServerFeatures property of type IFeatureCollection. Kestrel and HTTP.sys only expose a single feature each, IServerAddressesFeature, but different server implementations may expose additional functionality. IServerAddressesFeature can be used to find out which port the server implementation has bound at runtime.

The property is a collection, so you'll need to filter for specific hosting methods that pertain to IIS Reverse Proxy and Kestrel.




回答2:


The easiest way is probably reading System.Diagnostics.Process.GetCurrentProcess().ProcessName. If it is w3wp or iisexpress you know the host is IIS/IIS Express, while dotnet (or other names when you use self-contained deployment) indicates Kestrel. This will only work for an in process deployment. If you are out of process, this will not work. Learn more at https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/aspnet-core-module

Example:

/// <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));
}


来源:https://stackoverflow.com/questions/55852820/check-if-hosting-server-is-iis-or-kestrel-at-runtime-in-aspnet-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!