HttpContentExtensions.ReadAsAsync<string>
和HttpContent.ReadAsStringAsync
应该用于什么?
它们似乎做着相似的事情,但使用方式却很奇怪。以下是一些测试及其输出结果。在某些情况下,会抛出JsonReaderException
异常,在某些情况下,JSON会被输出,但带有额外的转义字符。
我已经在我的代码库中使用了这两个函数,但希望能够理解它们应该如何工作,以便选择一个进行对齐。
//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\"}"
ReadAsAsync<T>
可能只是一个包装器,用于JsonConvert.DeserializeObject<T>(await ReadAsStringAsync())
。 - Camilo TerevintoReadAsAsync<T>
更加聪明,因为它不会先将字符串读入内存再创建对象。 - DavidG