Ale*_*exD 5 c# webrequest httpwebresponse
我正在使用System.Net.WebRequest从某些API获取信息.当我收到错误时,响应只包含基本的HttpStatusCode和消息,而不是返回完整的错误.为了进行比较,在POSTMAN等工具中运行相同的发布数据和标头将返回该API的完整错误.
我想知道是否有一些属性或方式我可以获得完整的错误响应?
这是我正在运行的代码:
public HttpStatusCode GetRestResponse(
string verb,
string requestUrl,
string userName,
string password,
out string receiveContent,
string postContent = null)
{
var request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = verb;
if (!string.IsNullOrEmpty(userName))
{
string authInfo = string.Format("{0}:{1}", userName, password);
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers.Add("Authorization", "Basic " + authInfo);
}
if (!string.IsNullOrEmpty(postContent))
{
byte[] byteArray = Encoding.UTF8.GetBytes(postContent);
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = byteArray.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
try
{
using (WebResponse response = request.GetResponse())
{
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
receiveContent = reader.ReadToEnd();
reader.Close();
return ((HttpWebResponse) response).StatusCode;
}
}
}
catch (Exception ex)
{
receiveContent = string.Format("{0}\n{1}\nposted content = \n{2}", ex, ex.Message, postContent);
return HttpStatusCode.BadRequest;
}
receiveContent = null;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我生成一个向我显示错误的请求时,我会收到错误消息:The remote server returned an error: (400) Bad Request.并且没有InnerException,没有其他任何我可以从异常中受益.
[答案] @Rene指向正确的方向,可以像这样获得正确的反应体:
var reader = new StreamReader(ex.Response.GetResponseStream());
var content = reader.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)
您正在捕获通用异常,因此没有足够的空间来存储特定信息。
您应该捕获由几个webrequest类引发的特殊异常,即WebException
您的捕获代码可能是这样的:
catch (WebException e)
{
var response = ((HttpWebResponse)e.Response);
var someheader = response.Headers["X-API-ERROR"];
// check header
var content = response.GetResponseStream();
// check the content if needed
if (e.Status == WebExceptionStatus.ProtocolError)
{
// protocol errors find the statuscode in the Response
// the enum statuscode can be cast to an int.
int code = (int) ((HttpWebResponse)e.Response).StatusCode;
// do what ever you want to store and return to your callers
}
}
Run Code Online (Sandbox Code Playgroud)
在WebException实例中,您还可以访问Response来自主机的发送,因此您可以访问发送给您的任何内容。