簡體   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)

我正在研究由兩個模塊組成的ASP.NET Webapp:

  • 提供網絡服務端點的“ API”模塊
  • “ UX”模塊,調用這些端點

簡化后,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子句中的httpResponsenull )。

在我的首選方案中,我想避免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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM