Don’t use HostingEnvironment.ApplicationHost.GetSiteName()

We have developed a diagnostics framework we use to get some quick diagnostic information about our applications like whether a database or web service can be made.  It’s a server/app configuration smoke test of sorts.  Over time we’ve added further capabilities to it like checking registry entries exist, file/folder permissions and web/machine.config values. 

Our latest enhancement to the framework was to add some performance indicators like memory usage and IIS requests per second.  In order to retrieve IIS requests per second we need to know the site name because IIS provides these metrics on a per site basis.  Like every good developer I googled with Bing and used the first result we found which suggested using the following method:

System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();

This worked great in locally and in DEV but we received the following error in our QA environment.

Exception information:

    Exception type: SerializationException

    Exception message: Type is not resolved for member ‘Microsoft.IdentityModel.Claims.ClaimsPrincipal,Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’.

   at System.Web.Hosting.IApplicationHost.GetSiteName()

 

I’ve seen this before when we hadn’t bin deployed a needed reference but in this case it was there.  I dug for several hours thinking there was something wrong with my reference or the deployed dll version was wrong to no avail.

After further thought and review of the stack trace I identified that the GetSiteName call must be to blame.  Finally, I found the following SO post which highlighted ApplicationHost.GetSiteName() is not intended to be called from your code.  Instead, you should use the HostingEnvironment.SiteName property.

http://stackoverflow.com/a/17327189

System.Web.Hosting.HostingEnvironment.SiteName;

And that fixed it for us.  Apparently, this method use the GACed version explicitly instead of using the bin version.  Not sure why.

The moral of this story is don’t just use your first Bing result and call it day.  Spend 5 more minutes to read the full post or check a few more results.

1 thought on “Don’t use HostingEnvironment.ApplicationHost.GetSiteName()”

Leave a Reply to Martin Roth Cancel reply