14

应该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\"}"
4

1 回答 1

11

ReadAsStringAsync:这是一个基本的“以字符串形式获取内容”的方法。它适用于你扔给它的任何东西,因为它只是字符串。

ReadAsAsync<T>:这意味着用于将 JSON 响应反序列化为对象。它失败的原因是返回中的 JSON 不是单个字符串的有效 JSON 表示。例如,如果您序列化一个字符串:

var result = JsonConvert.SerializeObject("hello world");
Console.WriteLine(result);

输出是:

"hello world"

注意它是如何被双引号括起来的。如果您尝试将任意 JSON 直接反序列化为格式不正确的字符串,"....."则会抛出您看到的异常,因为它期望 JSON 以".

于 2018-06-28T00:23:51.037 回答