[英]ReadAsAsync keeps returning null WPF
我正在尝试获取 bin 为“0001”的数据
string bin = "0001"
HttpClient client = new HttpClient();
string uri = $"https://localhost:44316/api/Bplo?bin={bin}";
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<BploModel>();
return result;
}
else
{
throw new Exception(response.ReasonPhrase);
}
尝试将其添加到列表中,但仍返回 null。
查看您的屏幕截图,您的端点似乎正在使用合理的 JSON 进行回复,您的模型似乎没问题,并且您从调用中获得了 HTTP 200。
我深入研究了框架的ReadAsAsync<>
方法,并分解了它的组件,以便您可以逐步查看哪个部分失败了:
public static async Task<T> MyReadAsAsync<T>(string url)
{
var response = await new HttpClient().GetAsync(url);
response.EnsureSuccessStatusCode(); // Throw up if unsuccessful
/*** ReadAsAsync<> starts here ***/
// Check the header for content type
var contentType = response.Content.Headers.ContentType;
// Expected "application/json"
Debug.WriteLine($"ContentType: {contentType}");
// Get available formatters in the system
var formatters = new MediaTypeFormatterCollection();
// Expected: more than 0
Debug.WriteLine($"Formatters: {formatters.Count}");
// Find the appropriate formatter for the content
var formatter = formatters.FindReader(typeof(T), contentType);
// Expected: JsonMediaTypeFormatter
Debug.WriteLine($"Formatter: {formatter}");
// Check the formatter
var canRead = formatter.CanReadType(typeof(T));
// Expected: true
Debug.WriteLine($"CanReadType: {canRead}");
// Check the stream
var stream = await response.Content.ReadAsStreamAsync();
// Expected: length of your JSON
Debug.WriteLine($"StreamLength: {stream.Length}");
// Expected: your JSON here
Debug.WriteLine(System.Text.Encoding.UTF8.GetString(
(stream as System.IO.MemoryStream)?.ToArray()));
// Check the formatter reading and converting
// from the stream into an object
var resultObj = await formatter.ReadFromStreamAsync(
typeof(T), stream, response.Content, null);
// Expected: an object of your type
Debug.WriteLine($"Obj: {resultObj}");
// Cast to the proper type
var result = (T)resultObj;
// Expected: an object of your type
Debug.WriteLine($"Result: {result}");
return result;
}
您可以通过传入您的 url 来调用该方法(另请参阅Fiddle以获取针对公共端点的工作测试)
var result = await MyReadAsAsync<BploModel>("https://YOUR_ENDPOINT");
只需在 ReasAsAsync 末尾添加 .Result()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.