Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...