You need to enable JavaScript to run this app. 如何在Azure C# HTTP触发函数中读取请求体JSON属性值
优惠活动
大模型
产品
解决方案
定价
更多

如何在Azure C# HTTP触发函数中读取请求体JSON属性值

问题根因

无法获取到ComputerModel值的核心原因是取值渠道和值的实际存放位置不匹配:

  • req.Query["ComputerModel"] 仅能读取URL后拼接的查询参数(即https://函数地址/api/触发方法?ComputerModel=xxx这类传参形式携带的值)
  • 你的ComputerModel字段实际放置在POST请求的JSON格式请求体中,完全不属于查询参数范畴,自然无法通过该方式取到值。
修正实现方案

你已经将请求体内容读取为requestBody字符串,只需要对该JSON字符串做解析,即可提取对应字段,无需额外定义实体类,使用.NET内置的System.Text.Json就能轻量实现兼容查询参数、请求体双渠道取值的逻辑。

修正后可直接运行的代码

using System.Text.Json;

public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
    HttpRequest req, ILogger log)
{
    // 读取请求体原始内容
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    string computermodel = string.Empty;

    // 优先兼容原有查询参数传参的逻辑
    if (!string.IsNullOrEmpty(req.Query["ComputerModel"]))
    {
        computermodel = req.Query["ComputerModel"];
    }
    // 查询参数无值时,从请求体JSON中解析提取
    else if (!string.IsNullOrEmpty(requestBody))
    {
        using JsonDocument doc = JsonDocument.Parse(requestBody);
        // 检查JSON根节点是否存在ComputerModel键
        if (doc.RootElement.TryGetProperty("ComputerModel", out JsonElement cmElement))
        {
            computermodel = cmElement.GetString();
        }
    }

    string responseMessage = string.IsNullOrEmpty(computermodel) 
        ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
        : $"Hello, {computermodel}. This HTTP triggered function executed successfully.";

    return new OkObjectResult(responseMessage);
}
注意事项
  • 你提供的调试JSON存在格式语法问题:"ComputerModel": "Testings" 行末尾缺失逗号,实际发起请求时需保证JSON格式标准合法,否则解析逻辑会抛出异常。
  • 原有代码存在两处编译级错误:定义的变量名为全小写开头的computermodel,但空值判断时使用了大小写不一致的Computermodel(C#区分大小写,属于两个完全不同的变量);输出逻辑中引用了从未定义的name变量,参考代码中已同步修正。
  • 若后续需要提取嵌套层级的JSON字段(例如ComputerModel放置在Properties节点下),仅需调整TryGetProperty的逐级查找路径即可,无需引入第三方JSON解析库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.07 08:54:10