当.NET抛出WebException((400)Bad Request)时,如何处理WebResponse? [英] How to process WebResponse when .NET throws WebException ((400) Bad Request)?

查看:197
本文介绍了当.NET抛出WebException((400)Bad Request)时,如何处理WebResponse?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Facebook Graph Api and trying to get user data. I'm sending user access token and in case this token is expired or invalid Facebook returns status code 400 and this response:

{
    "error": {
        "message": "Error validating access token: The session is invalid because the user logged out.",
        "type": "OAuthException"
    }
}

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

The problem is that when I use this C# code:

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

如果状态代码是400 .NET抛出WebException,我的 webResponse null 被抓住,所以我没有机会处理它。我想这样做,以确保问题是过期的令牌,而不是其他地方。

If status code is 400 .NET throws WebException and my webResponse is null after exception is caught so I have no chance to process it. I want to do it to make sure that the problem is in expired token and not somewhere else.

有没有办法?

谢谢。

推荐答案

使用这样的try / catch块并适当地处理错误信息工作正常:

Using a try/catch block like this and processing the error message appropriately should work fine:

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

然而,使用 Facebook C#SDK 使这一切变得非常简单,因此您无需自行处理。

However, using the Facebook C# SDK makes this all really easy so that you don't have to process this yourself.

这篇关于当.NET抛出WebException((400)Bad Request)时,如何处理WebResponse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆