我想在我的应用程序中调用外部Api,如果超时异常抛出,则调用Api后,我的应用程序返回结果。现在我想模拟这种情况。这是我的代码:
public string Sample()
{
try
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response =
client.GetAsync("ExternalApi").GetAwaiter().GetResult();
//...
}
}
catch (Exception e)
{
return ((HttpRequestException) e).StatusCode == HttpStatusCode.RequestTimeout ? "timeOut" : "Error";
}
return "Success";
}
如果我在ExternalApi抛出TimeoutExceptionthen inSample方法我得到内部服务器错误。如何创建人工超时异常?
HttpClient类有一个Timeout属性。
所以试试这个
using (HttpClient client
= new HttpClient(){Timeout=new TimeSpan(0,5,0)})
设置5分钟的超时时间。
如果超时,你会得到一个webeexception。
为此,我最后使用了一个名为"Hercules Setup Utility"的应用程序。这个应用程序监听一个端口在"Tcp服务器"中获取您的请求,但根本没有响应。在执行这个应用程序并监听端口之后,你必须设置像localhost:port这样的内容。你会得到一个超时异常。
HttpClient类有一个Timeout属性。或者你可以使用一些应用程序来创建超时,比如Hercules Setup Utility
我最近使用Task方法替代Tracert,以便在发送DNS信息请求出错时获得异常。我猜你应该使用Task<>。看一下MSDN的主要解释:
https://learn.microsoft.com/en us/dotnet/api/system.threading.tasks.task?view=net - 5.0
我也认为你可以欣赏我如何检查成功或异常在我自己的代码。看一下布尔DNS检查中的代码:
具有DNS功能的Tracert的替代类