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

.NET 6 Minimal API为何返回JSON字符串而非JSON格式数据?

.NET 6 Minimal API 透传第三方JSON数据的解决方案

方案1:直接转发原始HttpContent(推荐)

这是最简洁且避免序列化问题的方式,无需手动处理JSON字符串,直接将第三方API的响应流返回给客户端:

app.MapGet("/proxy", async (HttpClient client) =>
{
    var thirdPartyUrl = "第三方API的请求地址";
    var thirdPartyResponse = await client.GetAsync(thirdPartyUrl);

    // 透传第三方API的状态码
    if (!thirdPartyResponse.IsSuccessStatusCode)
    {
        return Results.StatusCode((int)thirdPartyResponse.StatusCode);
    }

    // 直接返回原始响应流,并携带正确的Content-Type
    var stream = await thirdPartyResponse.Content.ReadAsStreamAsync();
    var contentType = thirdPartyResponse.Content.Headers.ContentType?.ToString() ?? "application/json";
    return Results.Stream(stream, contentType);
});

方案2:返回原始JSON字符串并指定Content-Type

如果需要先读取JSON字符串做简单处理(比如日志记录),可以通过Results.Text指定正确的媒体类型,避免二次序列化导致的转义问题:

app.MapGet("/proxy", async (HttpClient client) =>
{
    var thirdPartyUrl = "第三方API的请求地址";
    var thirdPartyResponse = await client.GetAsync(thirdPartyUrl);

    if (!thirdPartyResponse.IsSuccessStatusCode)
    {
        return Results.StatusCode((int)thirdPartyResponse.StatusCode);
    }

    var rawJson = await thirdPartyResponse.Content.ReadAsStringAsync();
    // 这里可以添加日志、简单修改等操作
    return Results.Text(rawJson, "application/json");
});

为什么之前的方法会出问题?

  • 直接返回字符串时,Minimal API默认会将其视为纯文本进行序列化,导致JSON被转义;
  • 使用JsonConvert.DeserializeObject<dynamic>出现空数组,大概率是因为第三方返回的JSON存在语法错误(比如你示例中的AnArray是数组格式却包含键值对,应为对象数组[{"Id":11,"AnotherId":22}]),且动态反序列化对格式敏感,结构不确定时不建议使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:12:24