简体   繁体   中英

C# ReadAsAsync returning null when Postman returns data

I have an api, which actually calls another api internally and passes back those results.

httpClient.DefaultRequestHeaders.Authorization =
     new AuthenticationHeaderValue("Bearer", BearerToken);

HttpResponseMessage response = await httpClient.GetAsync(fullUrlPath);
if (response.IsSuccessStatusCode)
{
     return Ok(await response.Content.ReadAsAsync<Sheet>());
}
return BadRequest();

It hits the response.IsSuccessStatusCode and goes into the ReadAsAsync method, but the data returns null. I've tested the same in postman and got data. Not sure if it's a syntax I'm missing. The data object was copied from the postman response.

Similar problem happened to me once,

I found this is cause by NewtonSoft.Json not working as expected. When deserialization, It cannot match to the correct Json Property, which probly caused receving a null content.

If facing the problem, you can first check the status code and print the output as string to see whether it has the content,

var res = await Response.Content.ReadAsStringAsync();

if the content seem right it probly caused by unsuccessful deserailization.

If you are facing the same problem as metioned above, the solution is simple:

Use: System.Text.Json.Serialization; JsonPropertyName("your_property")

using System.Text.Json.Serialization;

namespace Project.Models;

public class TokenResponse
{
    [JsonPropertyName("access_token")]
    public string AccessToken { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM