gpt4 book ai didi

c# - 读取 WebException 的响应流

转载 作者:行者123 更新时间:2023-11-30 19:43:20 25 4
gpt4 key购买 nike

我有以下方法,基本上是使用 Facebook 凭据对用户进行身份验证。出于某种原因,我在尝试处理授权 key (代码)时收到了 WebException。因此,我尝试读取响应流以了解发生了什么,但在读取流时我不断出错。这是我的代码:

    private void OnAuthCallback(HttpContextWrapper context, WebServerClient client)
{
try
{
IAuthorizationState authorizationState = client.ProcessUserAuthorization(context.Request);
AccessToken accessToken = AccessTokenSerializer.Deserialize(authorizationState.AccessToken);
String username = accessToken.User;
context.Items[USERNAME] = username;
}
catch (ProtocolException e)
{
if (e.InnerException != null)
{
String message = e.InnerException.Message;
if (e.InnerException is WebException)
{
WebException exception = (WebException)e.InnerException;
var responseStream = exception.Response.GetResponseStream();
responseStream.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(responseStream))
{
message = sr.ReadToEnd();
}
}
EventLog.WriteEntry("OAuth Client", message);
}
}
}

如果我删除 responseStream.Seek(0, SeekOrigin.Begin); 行,它会给我一个 ArgumentException 消息,指出流不可读。这条线就位后,它告诉我无法操作已经关闭的流。这个流是如何关闭的?为什么我不能从中读取?

最佳答案

您可以阅读响应的正文。我在 this answer 中找到了解决方案.

您应该将流转换为MemoryStream 并使用ToArray 方法,然后使用Encoding.UTF8.GetString 获取文本。

private void OnAuthCallback(HttpContextWrapper context, WebServerClient client)
{
try
{
IAuthorizationState authorizationState = client.ProcessUserAuthorization(context.Request);
AccessToken accessToken = AccessTokenSerializer.Deserialize(authorizationState.AccessToken);
String username = accessToken.User;
context.Items[USERNAME] = username;
}
catch (ProtocolException e)
{
if (e.InnerException != null)
{
String message = e.InnerException.Message;
if (e.InnerException is WebException)
{
WebException exception = (WebException)e.InnerException;
message = ExtractResponseString(webException);
}
EventLog.WriteEntry("OAuth Client", message);
}
}
}

public static string ExtractResponseString(WebException webException)
{
if (webException == null || webException.Response == null)
return null;

var responseStream =
webException.Response.GetResponseStream() as MemoryStream;

if (responseStream == null)
return null;

var responseBytes = responseStream.ToArray();
var responseString = Encoding.UTF8.GetString(responseBytes);
return responseString;
}

关于c# - 读取 WebException 的响应流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15453079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com