I don't use Newtonsoft.Json but I get an error saying it cannot be found

2.6k views Asked by At

I have a HttpSelfHostServer program that does NOT use Newtonsoft.Json library at all but I get the following error:

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)

My code:

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();
}

I do use Json.NET in other projects but not this one.

Error happens on this line

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

And there is no reference to it in app.config.

Appreciate your advice.

2

There are 2 answers

1
apros On

JSON.NET is an integral part of ASP.NET Web API. It has a bunch of features that are not supported by the DataContractJsonSerializer such as being much more flexible in what kind of types it can serialize and exactly how they should be serialized. You can find how it is uses in Web API following the next link

0
Tim Robbins On

Thank you guys I found the solution. Add this to your 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>

And you need to have Newtonsoft.Json.dll in your output directory.

EDIT: Apparently installing Json.NET from Nuget is a breaking change for older WebApi self hosting projects and you will need to reference Newtonsoft.Json.dll for them to work.

You also need to reference the following DLLs: System.Net.Http.dll, System.Net.Http.Formatting.dll, System.Web.Http.dll, System.Web.Http.SelfHost.dll

Have a nice day :)