简体   繁体   English

读取通过System.Net.Http.HttpClient(ASP.NET MVC)完成的不成功HTTP请求的响应

[英]Reading response of non-successful HTTP requests done via System.Net.Http.HttpClient (ASP.NET MVC)

I'm working on an ASP.NET webapp made of two modules: 我正在研究由两个模块组成的ASP.NET Webapp:

  • An "API" module, offering web service endpoints 提供网络服务端点的“ API”模块
  • An "UX" module, calling those endpoints “ UX”模块,调用这些端点

One of the endpoints in the API module looks like this when simplified: 简化后,API模块中的端点之一如下所示:

public class ReportingApiController: System.Web.Mvc.Controller
{
    [HttpPost]
    public async Task<ActionResult> Upload()
    {
        [...]
        return new HttpStatusCodeResult(540, "Failure parsing the file");
    }
}

The UX module calls that endpoint with code that looks like this: 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.
    }
}

I have noticed that the PostAsync() call throws an exception in the above example, because HTTP status codes 5XX are not successful. 我注意到在上面的示例中, PostAsync()调用引发了异常,因为HTTP状态代码5XX不成功。 Using a try/catch is ok, as long as I can still read the response code & message. 只要我仍然可以读取响应代码和消息,就可以try/catch使用try/catch Which hasn't been the case in my tests (I don't see that info in the exception, and httpResponse is null inside the catch clause). 在我的测试中情况并非如此(我没有在异常中看到该信息,并且catch子句中的httpResponsenull )。

In my preferred scenario, I would like to avoid a try/catch , simply have the PostAsync() call complete normally, and read the code & message in the httpResponse variable. 在我的首选方案中,我想避免try/catch ,只需使PostAsync()调用正常完成,并读取httpResponse变量中的代码和消息即可。

What do you recommend? 您有什么推荐的吗?

catch the WebException, it will return the original response. 捕获WebException,它将返回原始响应。 Here an example using String Builder to output headers and body from an HttpWebResponse. 这是一个使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM