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

如何在Azure门户的Azure函数中读取JSON文件数据

Azure Function 新增JSON文件上传支持修改方案

现有实现说明

  • 已开发HTTP触发型Azure Function,核心链路为:接收Postman发送的请求数据 → 数据写入Azure Blob Storage → 数据写入Azure Queue → 数据推送到指定Power BI数据集
  • 当前版本仅支持处理raw格式提交的JSON数据,暂不支持直接上传JSON文件的请求形式
  • 代码直接在Azure门户内编辑,已完成Blob Storage、Queue两个输出绑定的配置

现有代码

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log, TextWriter outputBlob, ICollector<string> outputQueueItem)
{

    string connString = "https://api.powerbi.com/beta/a5d051de-762f-4405-9401-3201d0670f2c/datasets/5cd0ca8f-ed39-4b14-b57e-684d1c0d1bd4/rows?redirectedFromSignup=1&key=3hr%2FH1zs7%2Fc9QY%2BRspBDhrip1T1dljq2MWG0h2cBoEb%2Frv%2Fi8SvPLay03vRLcqXc4OSaJOLZRoF51a1q7RNhoQ%3D%3D"; 
    
    string name = req.Query["name"]; 
    string number = req.Query["number"]; 

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody); 
    
    name = name ?? data?.name;
    number = number ?? data?.number;

    outputBlob.Write(name); 
    outputBlob.Write(number); 

    HttpClient client = new HttpClient();
    HttpContent content = new StringContent("[" + data + "]");
    HttpResponseMessage response = await client.PostAsync(connString, content);

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

                outputQueueItem.Add(name);
                outputQueueItem.Add(number);

            return new OkObjectResult(responseMessage);
}

具体修改点

  • 新增请求类型自动判断逻辑:如果请求是multipart/form-data格式(即上传文件的请求形式),自动读取上传的JSON文件内容做解析;如果是原有raw JSON格式,沿用原有读取逻辑,保证旧版调用方式不受影响
  • 修复原有逻辑缺陷:原Blob写入直接拼接name和number字段无分隔符,存储内容可读性差,改为写入完整结构化JSON;原Power BI推送直接拼接dynamic对象生成JSON字符串易出现转义错误,改为用Newtonsoft.Json做标准序列化;为Power BI推送请求添加application/json的Content-Type头,避免接口因格式校验拒绝请求
  • 统一数据校验逻辑:无论是Query参数、raw JSON传参还是JSON文件传参,都统一做字段空值校验

修改后可直接使用的代码

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Net.Http.Headers;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log, TextWriter outputBlob, ICollector<string> outputQueueItem)
{
    string connString = "https://api.powerbi.com/beta/a5d051de-762f-4405-9401-3201d0670f2c/datasets/5cd0ca8f-ed39-4b14-b57e-684d1c0d1bd4/rows?redirectedFromSignup=1&key=3hr%2FH1zs7%2Fc9QY%2BRspBDhrip1T1dljq2MWG0h2cBoEb%2Frv%2Fi8SvPLay03vRLcqXc4OSaJOLZRoF51a1q7RNhoQ%3D%3D"; 
    
    string name = req.Query["name"]; 
    string number = req.Query["number"];
    string requestBody;

    // 判断是否为文件上传请求
    if (req.HasFormContentType && req.Form.Files.Count > 0)
    {
        var file = req.Form.Files[0];
        // 校验上传文件为JSON格式
        if (file.ContentType != "application/json" && !file.FileName.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
        {
            return new BadRequestObjectResult("请上传JSON格式文件");
        }
        // 读取JSON文件内容
        using (var reader = new StreamReader(file.OpenReadStream()))
        {
            requestBody = await reader.ReadToEndAsync();
        }
    }
    else
    {
        // 原有raw JSON读取逻辑
        requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    }

    dynamic data = JsonConvert.DeserializeObject(requestBody); 
    
    name = name ?? data?.name;
    number = number ?? data?.number;

    // 参数校验
    if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(number))
    {
        return new BadRequestObjectResult("请传入name和number字段,支持Query参数、raw JSON、上传JSON文件三种传参方式");
    }

    // 写入Blob,存储完整结构化JSON
    string blobContent = JsonConvert.SerializeObject(new { name, number, uploadTime = DateTime.UtcNow });
    await outputBlob.WriteAsync(blobContent); 

    // 推送到Power BI,使用标准序列化避免格式错误
    HttpClient client = new HttpClient();
    HttpContent content = new StringContent(JsonConvert.SerializeObject(new[] { data }));
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    HttpResponseMessage response = await client.PostAsync(connString, content);

    // 写入队列
    outputQueueItem.Add(name);
    outputQueueItem.Add(number);

    string responseMessage = $"Hello, {name}. 函数执行成功,已完成Blob存储、队列写入、Power BI数据推送";
    return new OkObjectResult(responseMessage);
}

调用说明

  • 原有raw JSON调用方式无需修改,可正常使用
  • 上传JSON文件调用时,Postman选择form-data格式,Key类型选File,Value选择本地JSON文件即可,JSON文件内的字段结构和原有raw传参保持一致即可正常解析

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 19:57:27