Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HostingEnvironment does not contain a definition for IsHosted

Tags:

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

like image 283
Gianluca Ghettini Avatar asked Aug 16 '17 13:08

Gianluca Ghettini


1 Answers

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

like image 179
Brandon Avatar answered Sep 24 '22 11:09

Brandon