Accessing HTTP status code while using WCF client for accessing RESTful services

六眼飞鱼酱① 提交于 2019-12-12 01:15:49

问题


Thanks to this answer, I am now able to successfully call a JSON RESTful service using a WCF client. But that service uses HTTP status codes to notify the result. I am not sure how I can access those status codes since I just receive an exception on client side while calling the service. Even the exception doesn't have HTTP status code property. It is just buried in the exception message itself.

So the question is, how to check/access the HTTP status code of response when the service is called.


回答1:


As a quick win, you can access the status code in the exception like this:

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);
    }
}

Maybe there's a solution with a message inspector. But I haven't figured it out yet.




回答2:


A solution without WCF would be to use the HttpRequest and DataContractJsonSerializer classes directly:

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;
}


来源:https://stackoverflow.com/questions/4677052/accessing-http-status-code-while-using-wcf-client-for-accessing-restful-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!