Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 314
Charlie Avatar asked Apr 25 '19 15:04

Charlie


1 Answers

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));
}
like image 69
Lex Li Avatar answered Sep 27 '22 21:09

Lex Li