簡體   English   中英

ReadAsAsync 不斷返回 null WPF

[英]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);
    }
  • 狀態代碼為 200,但結果返回為空: 1

  • 我檢查了問題是否出在端點上,但效果很好: 2

  • 我試着檢查我是否拼錯了模型: 3

嘗試將其添加到列表中,但仍返回 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM