2011-09-30 92 views
34

我正在使用Facebook Graph Api并试图获取用户数据。我送用户访问令牌和的情况下,该令牌已过期或无效的Facebook返回状态代码400,这响应:当.NET抛出WebException((400)错误请求)时如何处理WebResponse?

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

的问题是,当我使用此C#代码:

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

如果状态代码是400,那么在异常被捕获后,.NET抛出WebException并且我的webResponsenull,所以我没有机会处理它。我想要做的是确保问题出现在已过期的令牌中,而不是其他地方。

有没有办法做到这一点?

谢谢。

回答

72

使用这样的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 
       } 
      } 
     } 
    } 
} 

然而,使用Facebook C# SDK使这一切很容易,这样你就不必处理这个自己。

+0

感谢您的详细解答,我用类似的方式完成了它。我知道我可以使用Facebook SDK,但与谷歌或Twitter相比,使用Facebook API相对容易,所以我决定在这里手动完成所有工作,以了解流程并拥有更多控制权。 – Burjua

+0

任何人都知道为什么WebException - > errorResponse.GetResponseStream()在Silverlight中为null?不过,我可以在小提琴手身上看到身体的反应。 –

+0

对我来说也是空的。做一点挖掘。这在正常.net编译时按预期工作。 –

14

WebExceptionResponse属性中仍然具有“真实”响应(假设完全有响应),因此您可以从catch块中获取该数据。

+0

感谢Jon,尝试访问'Response'属性是一个好主意吗?如果我在'catch'块中出现异常会发生什么?我应该把“try and catch”放在另一个'try and catch'里面吗? – Burjua

+0

@Burjua:访问属性不会给你一个例外 - 毕竟这就是它的存在。我相信*响应已经包含了所有的响应数据,所以如果你设法获取它,读取响应流本身应该是安全的。 –