Steve
Steve

Reputation: 4563

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

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.

Upvotes: 2

Views: 10057

Answers (1)

TheGeneral
TheGeneral

Reputation: 81583

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.

Upvotes: 11

Related Questions