What should `ReadAsAsync` and `ReadAsStringAsync` be used for?

后端 未结 1 1545
粉色の甜心
粉色の甜心 2021-01-11 13:24

What should HttpContentExtensions.ReadAsAsync and HttpContent.ReadAsStringAsync be used for?

They would seem to do similiar t

1条回答
  •  有刺的猬
    2021-01-11 14:24

    ReadAsStringAsync: This is a basic "get me the content as a string" method. It will work on anything you throw at it because it's just strings.

    ReadAsAsync: This is meant to be used to deserialise a JSON response into an object. The reason it fails is because the JSON in the return is not a valid JSON representation of a single string. For example, if you serialise a string:

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

    Output is:

    "hello world"
    

    Note how it is surrounded by double quotes. If you try to deserialise any arbitrary JSON directly into a string that isn't in the format "....." it will throw the exception you see because it is expecting the JSON to start with a ".

    0 讨论(0)
提交回复
热议问题