I am trying to convert a http response message into an IEnumerable, but I get the error:
JsonException: The JSON value could not be converted to System.Collections.Generic.IEnumerable 1[MyProject.Models.MyClass]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
Here is my code:
[HttpGet]
public async Task<IEnumerable<MyClass>> GetAsync()
{
var httpRequestMessage = new HttpRequestMessage(
HttpMethod.Get,
"https://xxx/api/123")
{
Headers =
{
{ HeaderNames.Authorization, "password" },
}
};
var httpClient = _httpClientFactory.CreateClient();
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
if (httpResponseMessage.IsSuccessStatusCode)
{
using var contentStream =
await httpResponseMessage.Content.ReadAsStreamAsync();
Ipads = await JsonSerializer.DeserializeAsync
<IEnumerable<MyClass>>(contentStream); // HERE IS WHERE THE ERROR HITS
}
return MyClasses;
}
Here is the same GET but in Postman working:
Thanks beforehand! Best regards Max
CodePudding user response:
You need to await the content from the HttpResponseMessage
as string.
var responseContent = await httpResponseMessage.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<MyClass>(responseContent);