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

.NET 6 API如何原样返回从Azure Function获取的JSON响应?

问题:如何将Azure Function返回的JSON原样返回给API调用方

我基于.NET 6开发了一个API,调用另一个Azure Function后获取到如下JSON数据:

{
    "serial_number": "0000",
     "Name": "abc"
}

我希望将该JSON原样返回给API调用方,但实际返回的响应格式如下:

{
  "message": "{\"serial_number\": \"0000\", \"Name\": \"abc\"}"
}

我的完整代码如下:

[HttpGet]
public async Task<IActionResult> mydevice()
{
    var url = _appSettings.mydevice;
   
    try
    {
        var response = await _Service.mydevice(url);
        string message = "Bad request";
        if (response != null)
        {
            message = await response.Content.ReadAsStringAsync();
            if (response.IsSuccessStatusCode)
                return Ok(new { message });
        }
        return BadRequest(new { message });
    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }
}
解决方案

问题核心是你把读取到的JSON字符串包装进了匿名对象new { message },ASP.NET Core会将这个匿名对象重新序列化为JSON,导致原始JSON被转义后成为message字段的取值。要实现需求,需直接返回原始JSON内容,而非包装后的对象,以下是两种可行修改方式:

方法一:返回ContentResult指定媒体类型

将成功分支的return Ok(new { message });替换为:

return Content(message, "application/json");

错误分支同步调整,避免额外包装:

return Content(message, "application/json", System.Text.Encoding.UTF8);

方法二:直接转发响应流(性能更优)

若无需修改返回的JSON,可直接将Azure Function的响应流转发给调用方:

if (response != null)
{
    if (response.IsSuccessStatusCode)
        return new FileStreamResult(await response.Content.ReadAsStreamAsync(), "application/json");
    else
    {
        var errorMessage = await response.Content.ReadAsStringAsync();
        return BadRequest(errorMessage);
    }
}

修改后的完整代码示例

[HttpGet]
public async Task<IActionResult> mydevice()
{
    var url = _appSettings.mydevice;
   
    try
    {
        var response = await _Service.mydevice(url);
        if (response != null)
        {
            if (response.IsSuccessStatusCode)
                return Content(await response.Content.ReadAsStringAsync(), "application/json");
            else
            {
                var errorMessage = await response.Content.ReadAsStringAsync();
                return BadRequest(errorMessage);
            }
        }
        return BadRequest("Bad request");
    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }
}

修改后API会直接返回从Azure Function获取的原始JSON结构,不再额外包裹message字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 08:55:02