Deployment issue: Could not load file or assembly ‘System.Web.Http’

Today I got an exception when deploying an ASP.NET MVC 4 application to our web server.

Could not load file or assembly 'System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified

It never happened to me before. The only change I did was small code change and package update. What really confused me was that my application doesn’t use System.Web.Http pacakge. I couldn’t see it anywhere in the solution, no matter in References or package.config or Web.config.

After long time checking of installed packages and assemblies, I used remote access to Web server and checked the bin folder of deployed project, System.Web.Http dll file was actually there and its version was 4.0. The reason i can come up with was that some of the packages i updated had dependency on System.Web.Http. But then the problem was “why can’t it be loaded by system?”

Inspired by one post related to this issue on StackOverflow, I tried a solution which added assembly redirects in Web.config like the following one. It resolved the issue.   

<dependentAssembly>
   <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
   <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
That means that some assembly is still referencing the older version of System.Web.Http which caused the problem. By using Assembly Binding Redirection, we are able to tell system bind to the newer version which is 4.0 in this case.