HttpResponseMessage' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter'

假如想象 提交于 2020-12-27 07:14:36

问题


I have this xUnit method in C# which test a web api

    [Fact]
    public async Task GetWeatherForecast()
    {
        var apiClient = new HttpClient();

        var apiResponse = await apiClient.GetAsync($"http://xxx/weatherforecast").Result;

        Assert.True(apiResponse.IsSuccessStatusCode);
    }

But hit this error HttpResponseMessage' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter'. If I removed async Task and await, it could run successfully.


回答1:


Don't call Result, it's likely to cause issues on the best of days when using the async and await pattern

 var apiResponse = await apiClient.GetAsync($"http://xxx/weatherforecast");

However, the problem is because you are trying to use a language feature associated with the await keywords that requires an awaitable. The compiler dictates that to await something it must satisfy certain constraints. An awaitable must implement the GetAwaiter method, INotifyCompletion, IsCompleted and GetResult method. Which is what the error message is describing.

This is due to the fact you have called the Result<T> method which returns the result value of a task (in this case the result from the Task returned from GetAsync<Task<T>>, your HttpResponseMessage). You are then trying to await it like it is a task / awaitable, which it is not.

In general, there are very few cases in the modern-era where calling Result, or Wait is actually a good idea.



来源:https://stackoverflow.com/questions/62419799/httpresponsemessage-does-not-contain-a-definition-for-getawaiter-and-no-acces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!