简体   繁体   中英

Json to HttpContent using streams

I have a class MyData which is Json serializable by using Json.Net JsonSerializer.Serialize(TextWriter, object) . I want to send this data (as json) to a web service via HttpClient.PostAsync .

Because converting the json to string and then sending it as StringContent is (probably) not performant, I want to do it with streams.

I found the class StreamContent , which takes a stream in its constructor. And serializing json into streams should be possible as well. So I tried this:

MyData data = ...; // already filled
string uri = ...;  // already filled
HttpClient client = new HttpClient();
JsonSerializer serializer = new JsonSerializer();
using (MemoryStream ms = new MemoryStream())
{
    using (StreamWriter sw = new StreamWriter(ms))
    using (JsonWriter jw = new JsonTextWriter(sw))
    {
        serializer.Serialize(sw, data);
        ms.Flush();
        ms.Position = 0;
    }
    HttpResponseMessage response = client.PostAsync(uri, new StreamContent(ms)).Result;
}

But running this code gives me two exceptions in the line HttpResponseMessage response = ... :

  1. HttpRequestException: Error when copying content into a stream.
  2. ObjectDisposedException: Could not access closed stream.

What am I doing wrong?

如果将对象序列化为MemoryStream ,则整个JSON数据将被写入缓冲区中,因此与仅序列化为字符串并使用StringContent没有显着的性能优势。

Your StremWriter disposes the memory stream before the request is sent, that is why you get the exceptions. You can either move your using statements to be in the same scope as the MemoryStream, or use the StreamWriter's constructor that accepts a boolean parameter to leave the stream open after the writer is disposed.

StreamWriter constructor :

Unless you set the leaveOpen parameter to true, the StreamWriter object calls Dispose() on the provided Stream object when StreamWriter.Dispose is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM