进行Web API调用时捕获异常

Max*_*eel 4 .net c# asp.net api http

我在C#代码中进行了很多Web API调用。我不知道如何捕捉错误。假设互联网连接无法正常工作,那么我的代码显示了运行时错误。我如何正确地将它们放入try catch块,一般规则是什么。我发现的所有文章都是关于如何抛出错误和错误消息的。
示例API调用:

 WebResponse webResponse = webRequest.GetResponse();
 string res = webResponse.ToString();
Run Code Online (Sandbox Code Playgroud)

using (var client = new HttpClient())
      client.BaseAddress = new Uri(CairoBaseUrl);
      var getStringTask = client.GetStringAsync(requestUrl);
      response = await getStringTask;
Run Code Online (Sandbox Code Playgroud)

和,

HttpResponseMessage response = await client.PostAsync(
                url,requestContent);
Run Code Online (Sandbox Code Playgroud)

Vol*_*hat 5

如果您正在调用asp.net Web API,我建议您使用HttpClient来完成此操作

 try    
  {
     HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
     response.EnsureSuccessStatusCode();
     string responseBody = await response.Content.ReadAsStringAsync();
     // Above three lines can be replaced with new helper method below 
     // string responseBody = await client.GetStringAsync(uri);

     Console.WriteLine(responseBody);
  }  
  catch(HttpRequestException e)
  {
     Console.WriteLine("\nException Caught!");  
     Console.WriteLine("Message :{0} ",e.Message);
  }
Run Code Online (Sandbox Code Playgroud)

这是来自MSDN的示例,该示例如何使用http客户端处理异常

在你的例子中,你有

using (var client = new HttpClient())
      client.BaseAddress = new Uri(CairoBaseUrl);
      var getStringTask = client.GetStringAsync(requestUrl);
      response = await getStringTask;
Run Code Online (Sandbox Code Playgroud)

但这是行不通的,因为await运算符只能与标记为async的方法一起使用,因此应该

  var getStringTask = await client.GetStringAsync(requestUrl);
Run Code Online (Sandbox Code Playgroud)