HttpClient PostAsJsonAsync incompatible with Newto

2020-04-07 18:37发布

问题:

Something I have just picked up in my winforms app

My app does an http call to a web Api service as follows

HttpClient _client = new HttpClient();
_client.Timeout = new TimeSpan(0, 3, 0);
_client.BaseAddress = new Uri("http://Myserver/MyApp");
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response =  _client.PostAsJsonAsync("api/Addin", newObject).Result;

Nothing fancy, but as soon as you install Newtonsoft.Json (V6.0.3) via nuget

suddenly I get a stackOverflow error on the HttpResponseMessage line of code. remove Newtonsoft, and problem is solved.

The problem is I was to use the library to serialize/deserialize data elsewhere in my form

My workaround was to use a different library, I am just using System.Runtime.Serialization.Json; but this is still really weird, no?

I should also add that this is dotnet v4.0 (not 4.5), and my app is a VSTO COM object running in MsWord as an Add On

I suspect a bug maybe in Newtonsoft

回答1:

Install the "microsoft asp.net web api 2.2 client libraries" from nuget and don't refer the system.net.http.dll and system.net.http.formatting.dll manually. If you install this package then will install the correct json.net as well



回答2:

If all you need is the PostAsJsonAsync method, you are better off writing your own extension method.

I recommend removing the reference to Microsoft.AspNet.WebApi.Client (when I use PostAsJsonAsync from this package, it complains that it can't find an older version of Newtonsoft.Json, but the thing is that I need the latest version. my project targets .net framework 4.7.2) anyhow...

Here is code that you can copy and paste.

I've used the fully qualified names so you don't have to worry about adding using statements.

I'm also using the Newtonsoft.Json library to serialize the object.

public static class HttpClientExt
{
    public static async System.Threading.Tasks.Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUrl, T theObj)
    {
        var stringContent = new StringContent(
            Newtonsoft.Json.JsonConvert.SerializeObject(theObj),
            System.Text.Encoding.UTF8, "application/json");
        return await client.PostAsync(requestUrl, stringContent);
    }
}

Modified from this answer: https://stackoverflow.com/a/40525794/2205372



回答3:

I received the error after updating to a newer version of the Newtonsoft.Json package.

Uninstalling the Microsoft.AspNet.WebApi.Client nugget package and reinstalling it after upgrading to the newer Newtonsoft.Json package resolved the issue for me.