问题描述
我正在尝试确定在使用 C# 和 .NET 4.5 的 404 错误的情况下由 HttpClient
的 GetAsync
方法返回的 response
.
I am trying to determine the response
returned by HttpClient
's GetAsync
method in the case of 404 errors using C# and .NET 4.5.
目前我只能判断发生了错误,而不能判断错误的状态,例如 404 或超时.
At present I can only tell that an error has occurred rather than the error's status such as 404 or timeout.
目前我的代码是这样的:
Currently my code my code looks like this:
static void Main(string[] args)
{
dotest("http://error.123");
Console.ReadLine();
}
static async void dotest(string url)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode.ToString());
}
else
{
// problems handling here
string msg = response.IsSuccessStatusCode.ToString();
throw new Exception(msg);
}
}
catch (Exception e)
{
// .. and understanding the error here
Console.WriteLine( e.ToString() );
}
}
我的问题是我无法处理异常并确定其状态和其他出错细节.
My problem is that I am unable to handle the exception and determine its status and other details of what went wrong.
我将如何正确处理异常并解释发生了什么错误?
How would I properly handle the exception and interpret what errors occurred?
推荐答案
您可以简单地查看 StatusCode
响应的属性:
You could simply check the StatusCode
property of the response:
static async void dotest(string url)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode.ToString());
}
else
{
// problems handling here
Console.WriteLine(
"Error occurred, the status code is: {0}",
response.StatusCode
);
}
}
}
这篇关于使用 HttpClient.GetAsync() 时如何确定 404 响应状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!