未捕获System.Net.WebException

时间:2012-07-09 17:25:09

标签: c# exception-handling httpwebrequest try-catch system.net.webexception

我发生了一个奇怪的问题。我有一些代码必须对客户端的服务器进行http发布。他们的帖子将内容返回给我,我需要向我的用户显示。如果你有问题,我想捕获错误并注入我自己的内容,让用户知道有问题。

这是我执行http post的静态助手类。

public static class HttpPostHelper
{
    public static string Post(string url, NameValueCollection values)
    {
        StringBuilder dataBuilder = new StringBuilder();

        foreach (var key in values.AllKeys)
        {
            EncodeAndAddItem(ref dataBuilder, key, values[key]);
        }

        Uri uri = new Uri(url);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = dataBuilder.Length;
        using (Stream writeStream = request.GetRequestStream())
        {
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] bytes = encoding.GetBytes(dataBuilder.ToString());
            writeStream.Write(bytes, 0, bytes.Length);
        }

        string result = String.Empty;

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
                {
                    result = readStream.ReadToEnd();
                }
            }
        }

        return result;
    }

    private static void EncodeAndAddItem(ref StringBuilder baseRequest, string key, string dataItem)
    {
        if (baseRequest == null)
        {
            baseRequest = new StringBuilder();
        }
        if (baseRequest.Length != 0)
        {
            baseRequest.Append("&");
        }

        baseRequest.Append(key);
        baseRequest.Append("=");
        baseRequest.Append(System.Web.HttpUtility.UrlEncode(dataItem));
    }
}

这是我的代码,它会发布帖子并返回内容。

private string GetReturnContent(string callback, NameValueCollection data, LogRequest request)
{
    string content = String.Empty;

    try
    {

        content = HttpPostHelper.Post(callback, data);

        request.Message = String.Format("Content Retrieved from Callback: {0}", content);

        logService.Debug(request);
    }
    catch (System.Net.WebException ex)
    {
        var response = ex.Response as HttpWebResponse;

        if (response != null)
        {
            if ((int)response.StatusCode == 403)
            {
                content = String.Format("The url {0} returned access denied (403).", callback);
                request.Message = content;
                logService.Warn(request);
            }
            else if ((int)response.StatusCode == 404)
            {
                content = String.Format("The url {0} returned page not found (404).", callback);
                request.Message = content;
                logService.Warn(request);
            }
            else if ((int)response.StatusCode == 405)
            {
                content = String.Format("The url {0} returned 405 error.  Please ensure the url is configured to accept http POST requests", callback);
                request.Message = content;
                logService.Warn(request);
            }
            else if ((int)response.StatusCode == 500)
            {
                content = String.Format("The url {0} returned a server error (500).", callback);
                request.Message = content;
                logService.Warn(request);
            }
            else
            {
                exceptionHandler.HandleError(ex);

                content = String.Format("The url {0} returned an error: {1}", callback, ex.Message);
                request.Message = content;
                logService.Error(request);
            }
        }
        else
        {
            exceptionHandler.HandleError(ex);

            content = String.Format("The url {0} returned an error: {1}", callback, ex.Message);
            request.Message = content;
            logService.Error(request);
        }
    }

    return content;
}

问题在于,无论如何,我总是会向我报告一个服务器错误(通过电子邮件报告处理程序,但这是另一个故事。我抓住了异常,我没有重新抛出它,然而我仍然收到错误报告。

  

例外:

     

System.Net.WebException:无法连接到远程服务器

     

内部异常消息:

     

System.Net.Sockets.SocketException:连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机未能响应[编辑]

堆栈跟踪指向此行作为PostHelper

中的罪魁祸首
using (Stream writeStream = request.GetRequestStream())
  System.Net.HttpWebRequest.GetRequestStream()

中的System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)

1 个答案:

答案 0 :(得分:2)

您收到套接字错误。在发送HTTP流量之前发生此错误(因此,没有状态代码)。

此块将被执行(因此您的错误电子邮件通知):

exceptionHandler.HandleError(ex);

content = String.Format("The url {0} returned an error: {1}", callback, ex.Message);
request.Message = content;
logService.Error(request);