如果我中止请求,我有一个WebException。我如何检查请求是否中止?
// if (asynchronousResult.AsyncState !="Aborted" ) {
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);//WebException if aborted
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
do_after(streamRead.ReadToEnd());
streamResponse.Close();
streamRead.Close();
response.Close();
// }
答案 0 :(得分:4)
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);//WebException if aborted
}
catch(WebException e)
{
if(e.Status == WebExceptionStatus.RequestCanceled)
{
//WORK
}
}
来自文档:
Abort
方法取消对资源的请求。取消请求后,调用BeginGetResponse
,EndGetResponse
,BeginGetRequestStream
或EndGetRequestStream
方法会导致WebException
设置Status
属性为RequestCanceled
{{1}}。
资料来源:http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.abort(v=VS.95)
答案 1 :(得分:1)
您应该将EndGetResponse包装在try-catch块中。如果Web请求中止,您将面临意外流,因此异常是处理此问题的最佳方法。