Skip to main content
 首页 » 编程设计

c#之我不使用 Newtonsoft.Json,但收到一条错误消息,提示无法找到它

2024年02月06日12haluo1

我有一个根本不使用 Newtonsoft.Json 库的 HttpSelfHostServer 程序,但我收到以下错误:

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. 
 
at System.Net.Http.Formatting.JsonMediaTypeFormatter..ctor() 
at System.Net.Http.Formatting.MediaTypeFormatterCollection.CreateDefaultFormatters() 
at System.Net.Http.Formatting.MediaTypeFormatterCollection..ctor() 
at System.Web.Http.HttpConfiguration.DefaultFormatters() 
at System.Web.Http.HttpConfiguration..ctor(HttpRouteCollection routes) 
at System.Web.Http.SelfHost.HttpSelfHostConfiguration..ctor(Uri baseAddress) 
at System.Web.Http.SelfHost.HttpSelfHostConfiguration..ctor(String baseAddress) 

我的代码:

using System; 
using System.Web.Http; 
using System.Web.Http.SelfHost; 
using System.Runtime.InteropServices; 
using System.IO; 
 
var selfHostConfiguraiton = new HttpSelfHostConfiguration("http://localhost:8080"); <- Error 
 
selfHostConfiguraiton.Routes.MapHttpRoute( 
  name: "DefaultApiRoute", 
  routeTemplate: "endpoints/{controller}", 
  defaults: null); 
 
using (var server = new HttpSelfHostServer(selfHostConfiguraiton)) 
{ 
  Console.WriteLine("Server started"); 
  server.OpenAsync().Wait(); 
} 

我确实在其他项目中使用 Json.NET,但不是这个。

错误发生在这一行

var selfHostConfiguraiton = new HttpSelfHostConfiguration("http://localhost:8080"); 

并且在 app.config 中没有引用它。

感谢您的建议。

请您参考如下方法:

谢谢你们,我找到了解决方案。将此添加到您的 app.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> 

并且您的输出目录中需要有 Newtonsoft.Json.dll。

编辑: 显然,从 Nuget 安装 Json.NET 对较旧的 WebApi 自托管项目来说是一个重大变化,您需要引用 Newtonsoft.Json.dll 才能使它们正常工作。

您还需要引用以下 DLL: System.Net.Http.dll、System.Net.Http.Formatting.dll、System.Web.Http.dll、System.Web.Http.SelfHost.dll

祝你有美好的一天:)