当.NET抛出WebException((400)Bad Request)时如何处理WebResponse?

Bur*_*jua 37 c# asp.net facebook exception httpwebresponse

我正在使用Facebook Graph Api并尝试获取用户数据.我正在发送用户访问令牌,如果此令牌过期或无效Facebook返回状态代码400并且此响应:

{
    "error": {
        "message": "Error validating access token: The session is invalid because the user logged out.",
        "type": "OAuthException"
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是当我使用这个C#代码时:

try {
   webResponse = webRequest.GetResponse(); // in case of status code 400 .NET throws WebException here
} catch (WebException ex) {
}
Run Code Online (Sandbox Code Playgroud)

如果状态代码为400,则.NET抛出WebException,并且在异常被捕获之后我webResponse就是null这样,所以我没有机会处理它.我想这样做是为了确保问题是在过期的令牌中,而不是在其他地方.

有办法吗?

谢谢.

bka*_*aid 88

使用像这样的try/catch块并适当地处理错误消息应该可以正常工作:

    var request = (HttpWebRequest)WebRequest.Create(address);
    try {
        using (var response = request.GetResponse() as HttpWebResponse) {
            if (request.HaveResponse && response != null) {
                using (var reader = new StreamReader(response.GetResponseStream())) {
                    string result = reader.ReadToEnd();
                }
            }
        }
    }
    catch (WebException wex) {
        if (wex.Response != null) {
            using (var errorResponse = (HttpWebResponse)wex.Response) {
                using (var reader = new StreamReader(errorResponse.GetResponseStream())) {
                    string error = reader.ReadToEnd();
                    //TODO: use JSON.net to parse this string and look at the error message
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,使用Facebook C#SDK使这一切变得非常简单,这样您就不必自己处理.


Jon*_*eet 14

WebException仍然有在"真实"的响应Response特性(假设有在所有的响应),以便可以从该中获取数据catch块.