我正在编写一个asp.net core web API,它正在消费另一个第三方API,并向调用者(即客户端Web浏览器)返回一些JSON响应。当我以异步方式编写我的实现时,Visual Studio建议从以下异步方法中删除async await。
我只是想澄清一下,我不需要将这两个方法包装在async await中吗?
以下是方法:
public async Task<T> GetAsync<T>(string url)
{
return await GetResponse<T>(HttpMethod.GET,url);
}
public async Task<T> PostAsync<T>(string url, object payload)
{
return await GetResponse<T>(HttpMethod.POST, url,payload);
}
以下是被上述两种方法调用的方法:
public async Task<T> GetResponse<T>(HttpMethod method,string url, object payload = null)
{
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
HttpResponseMessage response;
switch (method)
{
case HttpMethod.POST:
{
var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
response = await client.PostAsync(url, content).ConfigureAwait(false);
break;
}
case HttpMethod.GET:
default:
method = HttpMethod.GET;
response = await client.GetAsync(url).ConfigureAwait(false);
break;
}
var responseMessageString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
_logger.LogInformation($"{method.ToString()} {method.ToString()} {Environment.NewLine} Response: {responseMessageString}");
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseMessageString);
}
以下是来自Visual Studio的建议:
方法声明中的异步和await可能会被省略。
GetAsync
,PostAsync
)只是传递而没有其他方法在其中调用,因此您可以删除async-await并仅返回任务。 - Nkosi