![](/img/trans.png)
[英]Parallel HTTP requests using System.Net.Http.HttpClient
[英]Reading response of non-successful HTTP requests done via System.Net.Http.HttpClient (ASP.NET MVC)
我正在研究由两个模块组成的ASP.NET Webapp:
简化后,API模块中的端点之一如下所示:
public class ReportingApiController: System.Web.Mvc.Controller
{
[HttpPost]
public async Task<ActionResult> Upload()
{
[...]
return new HttpStatusCodeResult(540, "Failure parsing the file");
}
}
UX模块使用如下代码调用该端点:
public class ReportingController : System.Web.Mvc.Controller
{
private async Task Foo()
{
var requestContent = [...]
HttpResponseMessage httpResponse = await httpClient.PostAsync("api/ReportingApi/Upload", requestContent); // `httpClient` is a System.Net.Http.HttpClient
// How to read the response? Both the HTTP status code returned (540 in the example), and the corresponding message.
}
}
我注意到在上面的示例中, PostAsync()
调用引发了异常,因为HTTP状态代码5XX不成功。 只要我仍然可以读取响应代码和消息,就可以try/catch
使用try/catch
。 在我的测试中情况并非如此(我没有在异常中看到该信息,并且catch
子句中的httpResponse
为null
)。
在我的首选方案中,我想避免try/catch
,只需使PostAsync()
调用正常完成,并读取httpResponse
变量中的代码和消息即可。
您有什么推荐的吗?
捕获WebException,它将返回原始响应。 这是一个使用String Builder从HttpWebResponse输出标题和正文的示例。
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine($"Returned Status Code: {httpResponse.StatusCode.ToString()}");
using (Stream data = httpResponse.GetResponseStream())
{
for (var i = 0; i < httpResponse.Headers.Count; ++i)
{
stringBuilder.AppendLine($"{httpResponse.Headers.Keys[i]}: {httpResponse.Headers[i]}");
}
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
stringBuilder.AppendLine($"Body: {text}");
}
}
// do whatever
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.