ReadAsAsync不断返回空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);
    }
  • 状态码为200,但结果返回为空:

    1

  • 我检查了问题是否出在终点,但是工作得很好:

    2

  • 我尝试检查模型是否拼写错误

    3

试图将其添加到列表中,但仍返回null。

解决方法

查看您的屏幕截图,看来您的端点正在使用合理的JSON进行答复,您的模型似乎还可以,并且您从呼叫中获得了HTTP 200。

我挖了the framework's ReadAsAsync<> method,并分解了它的组成部分,以便您逐步了解哪个部分对您不利:

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;
}

您可以通过传入您的网址来调用该方法(有关对公共端点的有效测试,另请参见Fiddle

var result = await MyReadAsAsync<BploModel>("https://YOUR_ENDPOINT");
,

只需在ReasAsAsync的末尾添加.Result()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...