如何强制WebAPI使用JSON.net 6.0.3而不是4.5?

Bla*_*ise 14 c# json.net asp.net-web-api2 asp.net-mvc-5.1

添加WebAPI并注册后Global.asax.

我们发现我们的网络应用程序在此行中断:

Line 17:             GlobalConfiguration.Configure(WebApiConfig.Register);
Run Code Online (Sandbox Code Playgroud)

错误信息:

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, 
PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. 
The system cannot find the file specified.
Run Code Online (Sandbox Code Playgroud)

经过一些检查,我发现我们正在使用Json.net 6此MVC 5.1应用程序.这是否意味着我们要降级到Json.net 4.5的WebAPI工作吗?


在我的.csproj文件中,只有一个条目:

<Reference Include="Newtonsoft.Json, Version=6.0.3.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\packages\Newtonsoft.Json.6.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
  <Private>False</Private>
</Reference>
Run Code Online (Sandbox Code Playgroud)

当我查看我的内容Json.NET时Manage NuGet Packages,它也说我Json.NET的版本是6.0.3.

另外,bindingRedirect我的声明已经有了web.config.

  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
  </dependentAssembly>
Run Code Online (Sandbox Code Playgroud)

但是,如果我查看referencesvisual studio中的web项目.Newtonsoft.Json指向的路径C:\Program Files (x86)\Microsoft Visual Studio 12.0\Blend\Newtonsoft.Json.dll却Copy Local是错误的.

怎么可能?我们如何处理这场冲突?

Gil*_*dor 11

您需要在web.config中添加绑定重定向(可能与现有的绑定重定向合并):

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>
Run Code Online (Sandbox Code Playgroud)

  • @Blaise这是因为我几天前有完全相同的问题(在同一行上有相同的例外),这是解决方案. (3认同)

Der*_*ter 5

在我将 Web Api 更新到最新版本之前,重定向对我不起作用:

PM> update-package Microsoft.AspNet.WebApi.Client -Version 4.0.30506
Updating 'Microsoft.AspNet.WebApi.Client' from version '4.0.20710.0' to '4.0.30506.0' in project 'TestProject.Api'.
Run Code Online (Sandbox Code Playgroud)
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
  </dependentAssembly>
Run Code Online (Sandbox Code Playgroud)