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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With