You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从API的401 Unauthorized响应中提取自定义消息?

提取API 401响应中的自定义消息方法

当然可以提取自定义消息,问题出在你可能使用了EnsureSuccessStatusCode()这类会直接抛出通用异常的方法,导致忽略了API返回的响应体内容。具体处理步骤如下:

  • 避免直接调用EnsureSuccessStatusCode(),先获取完整的HttpResponseMessage对象
  • 检查响应状态码是否为401,若是则手动读取响应体内容

示例WinForm客户端代码:

using System.Net;
using System.Net.Http;
using System.Windows.Forms;

// 在异步方法中执行请求
async void RequestApi()
{
    using var client = new HttpClient();
    var response = await client.GetAsync("你的API接口地址");

    if (!response.IsSuccessStatusCode)
    {
        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            // 读取API返回的自定义消息
            string customMsg = await response.Content.ReadAsStringAsync();
            MessageBox.Show(customMsg, "未授权", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        else
        {
            MessageBox.Show($"请求错误: {response.StatusCode}", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        return;
    }

    // 处理成功响应逻辑
    string result = await response.Content.ReadAsStringAsync();
    // ...
}

原理说明:当你在API中用return Unauthorized("my custom message");返回响应时,自定义消息会被放在HTTP响应的响应体中,而默认的异常提示只是HttpClient根据状态码生成的通用文本,并没有读取响应体。只要绕过自动抛出异常的逻辑,手动读取响应体就能拿到自定义消息。

内容的提问来源于stack exchange,提问作者Hovi906

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 14:42:00