代码之家  ›  专栏  ›  技术社区  ›  James Wood

“readassync<string>”和“readasstringasync”应该用于什么?

  •  9
  • James Wood  · 技术社区  · 6 年前

    应该怎么做 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\"}"
    
    1 回复  |  直到 6 年前
        1
  •  7
  •   DavidG    6 年前

    ReadAsStringAsync

    ReadAsAsync<T>

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

    "hello world"
    

    注意它是如何被双引号包围的。如果尝试将任意JSON直接反序列化为不符合格式的字符串 "....." " .