如何在.NET抛出引发WebException((400)错误的请求)处理WebResponse的? [英] How to process WebResponse when .NET throws WebException ((400) Bad Request)?

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

问题描述

我使用Facebook的图形API,并试图获取用户数据。我发送用户访问令牌的情况下,该令牌已过期或无效Facebook的返回状态code 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:

{
   错误:{
      消息:错误验证访问令牌:会话是无效的,因为用户注销
      类型:OAuthException
   }
}

问题是,当我使用这个C#code:

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

如果状态code是400 .NET抛出引发WebException和我的 WebResponse类异常被捕获后,所以我没有机会对其进行处理。我想这样做,以确保该问题是已过期的令牌,而不是别的地方。

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.

有没有办法做到这一点?

Is there a way to do it?

感谢。

推荐答案

使用这样的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)错误的请求)处理WebResponse的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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