What should HttpContentExtensions.ReadAsAsync<string>
and HttpContent.ReadAsStringAsync
be used for?
They would seem to do similiar things but work in curious ways. A couple of tests and their outputs are below. In some cases JsonReaderException
are thrown, in some cases, the JSON is output but with additional escape characters.
I've ended up using both functions across my code base, but was hoping to align on one if I could understand how they were supposed to work.
//Create data and serialise to JSON
var data = new
{
message = "hello world"
};
string dataAsJson = JsonConvert.SerializeObject(data);
//Create request with data
HttpConfiguration config = new HttpConfiguration();
HttpRequestMessage request = new HttpRequestMessage();
request.SetConfiguration(config);
request.Method = HttpMethod.Post;
request.Content = new StringContent(dataAsJson, Encoding.UTF8, "application/json");
string requestContentT = request.Content.ReadAsAsync<string>().Result; // -> JsonReaderException: Error reading string.Unexpected token: StartObject.Path '', line 1, position 1.
string requestContentS = request.Content.ReadAsStringAsync().Result; // -> "{\"message\":\"hello world\"}"
//Create response from request with same data
HttpResponseMessage responseFromRequest = request.CreateResponse(HttpStatusCode.OK, dataAsJson, "application/json");
string responseFromRequestContentT = responseFromRequest.Content.ReadAsAsync<string>().Result; // -> "{\"message\":\"hello world\"}"
string responseFromRequestContentS = responseFromRequest.Content.ReadAsStringAsync().Result; // -> "\"{\\\"message\\\":\\\"hello world\\\"}\""
//Create a standalone new response
HttpResponseMessage responseNew = new HttpResponseMessage();
responseNew.Content = new StringContent(dataAsJson, Encoding.UTF8, "application/json");
string responseNewContentT = responseNew.Content.ReadAsAsync<string>().Result; // -> JsonReaderException: Error reading string.Unexpected token: StartObject.Path '', line 1, position 1.
string responseNewContentS = responseNew.Content.ReadAsStringAsync().Result; // -> "{\"message\":\"hello world\"}"