Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

asp.net-mvc-4asp.net-web-apiassembly-resolutionodata

Problem

After installing the Microsoft ASP.NET Web API OData package 5.0.0-rc1 prerelease I end up with the following exception:

Could not load file or assembly 'System.Web.Http, 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)

My MVC 4 project is brand new and really small, nothing fancy in it. I target .NET framework 4.5

I need this nuget package to implement PATCH using the Delta class
(When I use the version 4.0.0.0 of the package, the Delta class is not working).

How can I fix that?

My versions of System.Web.Http

In GAC I have version 5.0.0.0 of System.Web.Http

gacutil -l System.Web.Http The Global Assembly Cache contains the
following assemblies: System.Web.Http, Version=5.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35,
processorArchitecture=MSIL

In Visual Studio, when I browse assemblies, the given version of System.Web.Http is 4.0.0.0 (Why?)

In my project, the reference to System.Web.Http

  • Has the version 5.0.0.0
  • Points to the \lib\net45\ folder of the package
  • Has CopyLocal=true

Things I tried

I tried to bind redirect v 4.0.0.0 to 5.0.0.0 in Web.config

<dependentAssembly>
    <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="4.0.0.0-4.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>

But it gives me another exception:

Attempt by method 'System.Web.Http.GlobalConfiguration..cctor()' to
access field
'System.Web.Http.GlobalConfiguration.CS$<>9__CachedAnonymousMethodDelegate2'
failed.

I guess that v 4.0.0.0 really need to be used by core Web Api engine.

Linked questions

Code Analysis error Could not load file or assembly 'System.Net.Http, Version=2.0.0.0 in MVC4 Web API
Could not load file or assembly 'System.Net.Http, Version=2.0.0.0 in MVC4 Web API

Best Answer

Visual Studio 2013 has a new feature to take care of this. When you build the app, you should see warnings about different versions of an assembly being referenced. Double click the warning to add assembly binding redirects to the web.config.

See http://msdn.microsoft.com/en-us/library/2fc472t2.aspx for more details.

jeff.eynon notes below that you need to have the web.config checked out (if using TFS source control) to get VS to edit the file automatically. Thanks for the tip!