当.NET抛出WebException((400)错误请求)时如何处理WebResponse?
问题描述:
我正在使用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并且我的webResponse
为null
,所以我没有机会处理它。我想要做的是确保问题出现在已过期的令牌中,而不是其他地方。
有没有办法做到这一点?
谢谢。
答
使用这样的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使这一切很容易,这样你就不必处理这个自己。
感谢您的详细解答,我用类似的方式完成了它。我知道我可以使用Facebook SDK,但与谷歌或Twitter相比,使用Facebook API相对容易,所以我决定在这里手动完成所有工作,以了解流程并拥有更多控制权。 – Burjua
任何人都知道为什么WebException - > errorResponse.GetResponseStream()在Silverlight中为null?不过,我可以在小提琴手身上看到身体的反应。 –
对我来说也是空的。做一点挖掘。这在正常.net编译时按预期工作。 –