gpt4 book ai didi

c# - `ReadAsAsync` 和 `ReadAsStringAsync` 应该用来做什么?

转载 作者:可可西里 更新时间:2023-11-01 09:09:46 33 4
gpt4 key购买 nike

应该做什么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\"}"

最佳答案

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

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

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

输出是:

"hello world"

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

关于c# - `ReadAsAsync<string>` 和 `ReadAsStringAsync` 应该用来做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51073013/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com