我正在使用 Asp.Net WebClient 来发布 http 帖子。我尝试捕获代码以捕获 WebException。
try
{
using (MyWebClient wc = new MyWebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = _lender.ContentType;
wc.Timeout = 200;
return _lender.GetResult(wc.UploadString(_lender.PostUri, _lender.PostValues));
}
}
catch (WebException ex)
{
return new ServiceError(ex.Status.ToString());
}
我正在寻找的主要例外是超时。我已经扩展了 WebClient 以允许我设置超时。
当我将超时设置为 100 毫秒时,会按预期抛出异常。我可以按照示例获取 webexception 状态(它返回“timeout”),但是我也想返回状态代码。
如果我使用 ex.Response 向下钻取以获取 httpwebresponse,当我期待相关的状态代码时,我会返回一个空值。为什么我没有得到 HttpStatus.Request.Timeout?