使用WCF客户端访问RESTful服务时访问HTTP状态代码

时间:2011-01-13 05:22:23

标签: wcf json wcf-client wcf-rest

感谢this answer,我现在能够使用WCF客户端成功调用JSON RESTful服务。但该服务使用HTTP状态代码来通知结果。我不确定如何访问这些状态代码,因为我在调用服务时在客户端收到异常。即使异常也没有HTTP状态代码属性。它只是隐藏在异常消息中。

alt text

所以问题是,如何在调用服务时检查/访问响应的HTTP状态代码。

2 个答案:

答案 0 :(得分:1)

快速获胜,您可以访问以下异常中的状态代码:

try
{
    client.DoSomething();  // call the REST service
}
catch (Exception x)
{
    if (x.InnerException is WebException)
    {
        WebException webException = x.InnerException as WebException;
        HttpWebResponse response = webException.Response as HttpWebResponse;
        Console.WriteLine("Status code: {0}", response.StatusCode);
    }
}

也许有一个消息检查器的解决方案。但我还没想出来。

答案 1 :(得分:0)

没有WCF的解决方案是直接使用 HttpRequest DataContractJsonSerializer 类:

private T ExecuteRequest<T>(Uri uri, object data)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

    // If we have data, we use a POST request; otherwise just a GET request.
    if (data != null)
    {
        request.Method = "POST";
        request.ContentType = "application/json";
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(data.GetType());
        Stream requestStream = request.GetRequestStream();
        serializer.WriteObject(requestStream, data);
        requestStream.Close();
    }

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T));
    Stream responseStream = response.GetResponseStream();
    T result = (T)deserializer.ReadObject(responseStream);
    responseStream.Close();
    response.Close();
    return result;
}