“HttpClient”错误消息

本文关键字:消息 错误 HttpClient | 更新日期: 2023-09-27 18:14:11

我使用HttpClient从服务器的API获取响应。

这个API类似于:

/api/图片/{0}

其中{0}为图像名称。
{"green", "red", "blue"}

这样的图像名称只有三种可能的值

我不知道当前存在哪些图像,所以我对所有三个图像进行API调用:

  • /api/图片/绿色
  • /api/图片/红色
  • /api/图片/蓝色

HttpClient可能会返回许多错误消息,但是我想为

做一个特殊的例子:

响应状态码不显示成功:404 (not Found).

问题:是否有可能使HttpClient返回(在这种情况下)错误消息与404 ?

“HttpClient”错误消息

HttpResponseMessage类包含StatusCode属性,那么为什么不像这样处理它呢?

using (HttpClient client = new HttpClient())
{
    HttpResponseMessage response = await client.GetAsync(url);
    switch (response.StatusCode)
    {
           case System.Net.HttpStatusCode.NotFound: { /* return here anything you want on 404 */ } break;
           default: { /* default behavior */ } break;
    }
}

响应对象将有一个StatusCode属性,可以通过以下方式访问:

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                if (response.StatusCode != HttpStatusCode.OK)
...