5

I'm developing a C# application and I need to find out if I'm under IIS or not. I've seen some question on SO about using the HostingEnvironment.IsHosted method. Unfortunately if I write something like:

if (HostingEnvironment.IsHosted)
{
    // on IIS
}
else
{
   // not on IIS
}

I get a compile error:

HostingEnvironment does not contain a definition for IsHosted

I'm using: Microsoft.AspNetCore.Hosting; Microsoft.AspNetCore.Hosting.Internal;

EDIT

Tried using System.Web.Hosting.HostingEnvironment.IsHosted as suggested but it didn't work

enter image description here

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Gianluca Ghettini
  • 11,129
  • 19
  • 93
  • 159

2 Answers2

4

This might help. You could fetch the IHostingEnvironment like this:

var hostingEnvironment =(IHostingEnvironment)options.ApplicationServices.GetService(typeof(IHostingEnvironment))

if(hostingEnvironment.IsProduction())
{
    // do work
}

The environment is set in your launchSettings.json. Under your launch profiles:

"IIS Express": {
  "commandName": "IISExpress",
  "launchBrowser": true,
  "launchUrl": "/api/values",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development"
  }
},

Default value is "Production" when deployed.

EDIT: I'm actually missing a portion. You would be required to envelope code in .UseKestrel(options => { /* environment code */ })

Brandon
  • 404
  • 6
  • 21
0

What you mean is System.Web.Hosting.HostingEnvironment.IsHosted

https://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.ishosted(v=vs.110).aspx

Not sure what's the ASP.NET Core equivalent.

marsze
  • 15,079
  • 5
  • 45
  • 61