getData1Async()getData2Async()以下两种方法是否基本相同?如果是这样,为什么我在EnsureSuccessStatusCode()方法中不需要getData2Async()

class Program
{
    static void Main(string[] args)
    {
        try
        {
            string uri = "https://www.blahblah.com/getdata";
            Task<string> x = getData1Async(uri);
            System.Diagnostics.Debug.WriteLine(x.Result);
            Task<string> y = getData2Async(uri);
            System.Diagnostics.Debug.WriteLine(y.Result);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    static async Task<string> getData1Async(string uri)
    {
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(uri);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }

    static async Task<string> getData2Async(string uri)
    {
        var httpClient = new HttpClient();
        return await httpClient.GetStringAsync(uri);
    }
}

最佳答案

getData1Async-在这里,您将获得类型为HttpResponseMessage的对象,如果您不确定确保成功完成响应并调用response.Content.Read ...,答案将是不确定的。
getData2Async-直接调用httpClient本身以获取字符串,该字符串在内部确保仅当接收到数据时才返回。

关于c# - 使用HttpResponseMessage.EnsureSuccessStatusCode(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31668893/

10-10 22:56