云服务回收错误 System.IO.FileLoadException:无法加载文件或程序集“System.Web.Http,版本=4.0.0.0

Cloud Service Recycle with error System.IO.FileLoadException: Could not load file or assembly 'System.Web.Http, Version=4.0.0.0

我有一个针对 4.6.1 框架的 Web api 项目并将其部署为 Azure 上的云服务。部署时出现以下错误。

Web.Config 详情:

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

事件查看器出错:

无法创建角色入口点:System.TypeLoadException:由于以下异常,无法加载角色入口点: -- System.IO.FileLoadException: 无法加载文件或程序集 'System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' 或其依赖项之一。找到的程序集的清单定义与程序集引用不匹配。 (HRESULT 异常:0x80131040) 文件名:'System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

我的解决方案中没有引用 System.Web.Http,版本=4.0.0.0。请让我知道我做错了什么。

我们或许可以从中得到答案blog。它阐述了根本原因和解决方案。以下是博客的片段。

解法:

1) Open the .dll.config located in your project bin folder.

2) Check if there is the BindingRedirect entry that you need. If not, follow one of the two options below: a) Copy the web.config or app.config content (considering one of these two configuration files has the information that you need) and paste it into the .dll.config file. b) Manually create an Assembly Binding entry:

3) Add the .dll.config file to your Solution (same level as the web.config or app.config) and set the Copy to Output Directory property to “Copy Always”.

根本原因:

Usually, when a new assembly is added to your project, Visual Studio will automatically create a bindingRedirect entry in your web.config (Web Role) or app.config (Worker Role) just to avoid the wrong assembly version issue.

However, in Azure Cloud Services, the assembly bindings from web.config and app.config does not have effect, due to the fact that WaIISHost (Web Role) and WaWorkerHost (Worker Role) are not able to read these two configuration files, instead, they read the .dll.config file, and this is the file where the assembly binding configuration need to be