如何解析异步http帖子期间发生的内部服务器错误?

时间:2011-08-16 04:12:01

标签: http windows-phone-7

我正在做一些通常是Windows Phone 7上的简单http帖子(下面的代码)。当我在帖子中看到小提琴手时,我从服务器看到了这个结果

  

HTTP / 1.1 500内部服务器错误缓存控制:私有   Content-Type:application / json; charset = utf-8服务器:   Microsoft-IIS / 7.5 jsonerror:true X-AspNet-Version:2.0.50727   X-Server:www03 X-Site:prod日期:星期二,2011年8月16日03:49:51 GMT   内容长度:220

     

{“留言”:“我们很抱歉......}

当我试着抓住异步帖时,除了

之外我找不到任何东西
  

{System.Net.WebException:远程服务器返回错误:   未找到。 ---> System.Net.WebException:远程服务器返回了一个   错误:NotFoun ...

我的问题是:如何从此异常中获取实际消息(显示在fiddler中)?或者如何完全避免这个异常并将json返回,以便我可以解析它以获取实际的错误消息?

提前谢谢

    public void Checkout(ResponseAndCookies responseAndCookies)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/checkout");
        request.ContentType = "application/json";
        request.CookieContainer = responseAndCookies.CookieContainer;
        request.Method = "POST";
        request.AllowAutoRedirect = false;
        request.Accept = "application/json";

        request.BeginGetRequestStream(new AsyncCallback(GetRequest), request);
    }

    private void GetRequest(IAsyncResult asyncResult)
    {
        var json = "{\"valid\":true}";
        byte[] byteArray = Encoding.UTF8.GetBytes(json);

        HttpWebRequest request = (HttpWebRequest) asyncResult.AsyncState;
        Stream newStream = request.EndGetRequestStream(asyncResult);
        newStream.Write(byteArray, 0, byteArray.Length);
        newStream.Close();

        request.BeginGetResponse(new AsyncCallback(GetResponse), request);
    }

    private void GetResponse(IAsyncResult asyncResult)
    {
            var response = ReadResponse(asyncResult); //if I try catch this I get the exception listed above :(
    }

    private ResponseAndCookies ReadResponse(IAsyncResult result)
    {
        Stream dataStream = null;
        HttpWebRequest request = (HttpWebRequest) result.AsyncState;
        HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse;
        dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        reader.Close();
        dataStream.Close();
        response.Close();   

        var responseAndCookies = new ResponseAndCookies
                                     {CookieContainer = request.CookieContainer, Markup = responseFromServer};

        return responseAndCookies;
    }

1 个答案:

答案 0 :(得分:1)

HTTP 500与“未找到”(即HTTP 404)不同。所以你的例外实际上并不相关。无论如何,您显然需要阅读内容响应流。

您可以使用catch子句中的WebException.Response属性读取响应。

如果说的话,我建议你研究像RestSharp这样的框架。没有必要自己编写这么多代码。