[英]Unable to deserialize HttpResponseMessage to an object
I am working on IHttpClientFactory
in .net core 6 application to read httpClient data and object is to deserialize into object APIResponse
我正在IHttpClientFactory
核心 6 应用程序中使用 IHttpClientFactory 来读取 httpClient 数据,object 是反序列化为 object APIResponse
error
cannot convert string to System.IO.Stream
I have tried also ReadAsStreamAsync in which case get empty object.我也尝试过 ReadAsStreamAsync 在这种情况下得到空 object。
Calling below method
var dd = _httpClientServices.GetRequestAsync<APIResponse>(httpClientConfig, null);
var response = await httpResponseMessage.Content.ReadAsStreamAsync();
public class HttpClientServices : IHttpClientService
{
private readonly IHttpClientFactory _httpClientFactory;
public HttpClientServices(IHttpClientFactory httpClientFactory)
{
this._httpClientFactory = httpClientFactory;
}
public async Task<TResponse> GetRequestAsync<TResponse>(HttpClientConfig httpClientConfig, string token) where TResponse : class
{
try
{
var apiUri = QueryHelpers.AddQueryString(httpClientConfig.ClientAPIUrl, httpClientConfig.Parameters);
HttpClient httpClient = CreateClient(httpClientConfig, null);
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, apiUri);
HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
if (httpResponseMessage.IsSuccessStatusCode)
{
var response = await httpResponseMessage.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(response))
{
var responseData = await JsonSerializer.DeserializeAsync<TResponse>(response); //getting error here..............
}
}
}
catch (Exception ex)
{
throw;
}
return null;
}
API Response Object
public class APIResponse
{
public APIResponseStatus APIResponseStatus { get; set; }
public int RecordCount { get; set; }
public dynamic? ResponseData { get; set; }
}
DeserializeAsync only accepts a Stream
parameter, but response
response is a string
. DeserializeAsync只接受一个Stream
参数,但response
响应是一个string
。 There's no IO involved when deserializing an in-memory string, so a DeserializeAsync
for strings wouldn't be useful.反序列化内存中的字符串时不涉及 IO,因此字符串的DeserializeAsync
不会有用。
The first solution would be to use Deserialize
:第一个解决方案是使用Deserialize
:
var responseData = JsonSerializer.Deserialize<TResponse>(response);
The second would be to read the response as a stream and deserialize asynchronously.第二个是将响应作为流读取并异步反序列化。 This preserves memory for large responses because it doesn't have to allocate a string to contain the entire response before deserialization这为大型响应保留了内存,因为它不必在反序列化之前分配一个字符串来包含整个响应
var stream = await httpResponseMessage.Content.ReadAsStreamAsync();
var responseData = await JsonSerializer.DeserializeAsync<TResponse>(stream);
var apiResponse = await httpResponseMessage.Content.ReadFromJsonAsync<APIResponse>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.