我在c#代码中进行了很多web api调用。我不知道如何捕捉错误。假设,互联网连接不起作用,那么我的代码显示运行时错误。如何正确地将它们放入try catch块中,一般规则是什么。我找到的所有文章都是关于如何丢弃错误和错误信息 示例API调用:
WebResponse webResponse = webRequest.GetResponse();
string res = webResponse.ToString();
另外
using (var client = new HttpClient())
client.BaseAddress = new Uri(CairoBaseUrl);
var getStringTask = client.GetStringAsync(requestUrl);
response = await getStringTask;
和
HttpResponseMessage response = await client.PostAsync(
url,requestContent);
答案 0 :(得分: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);
}
这是MSDN如何使用http客户端
处理异常的示例在你的例子中你有
using (var client = new HttpClient())
client.BaseAddress = new Uri(CairoBaseUrl);
var getStringTask = client.GetStringAsync(requestUrl);
response = await getStringTask;
但它不会工作,因为await运算符只能用于标记为异步的方法,所以它应该是
var getStringTask = await client.GetStringAsync(requestUrl);