Could not load file or assembly 'System.Web.Http.WebHost'
We ran into this error when deploying a solution from the build server:
Could not load file or assembly 'System.Web.Http.WebHost, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Since this was a new web server and this solution used Nuget (and Nuget Package Restore) for Web Api, we assumed the Nuget packages needed to be updated but whatever type of updating we tried, we were unable to resolve the issue on the deployed web server. After all sorts of checking and confirming of installed packages and assemblies, we just deleted the packages folder on the build server (the one created by Nuget Package Restore):
And then a fresh build solved the problem!
We are not exactly sure what happened here but most likely Nuget Package Restore had pulled down a newer version of the System.Web.Http.WebHost assembly that was not compatible with our project. But we are not exactly sure why the Visual Studio project (MSBuild) kept trying to use the newer version instead of the proper version for the project reference. This project had been upgraded to .NET Framework 4.5 several weeks ago and then rolled back to .NET Framework 4.0 because of a different issue. This could explain where the incorrect version of System.Web.Http.WebHost came from but why Nuget Package Restore kept the wrong one is unknown and why the project kept building with the incorrect assembly is unknown too.
In any case, for anyone that runs into the same issue, delete your packages folder and let Nuget Package Restore pull a fresh set of assemblies.
Full Exception information:
Exception type: HttpException
Exception message: Could not load file or assembly 'System.Web.Http.WebHost, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
at System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app)
at System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers)
at System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context)
at System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context)
at System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext)
Could not load file or assembly 'System.Web.Http.WebHost, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
at Global.Application_Start(Object sender, EventArgs e)