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

如何在Azure Functions v2中返回帕斯卡命名(Pascal Case)格式的JSON?

解决Azure Functions返回JSON属性名自动小写的问题

这个问题我之前也碰到过——Azure Functions默认的JSON序列化策略会把定义的PascalCase属性名自动转换成camelCase,导致你得到{"nome":"TONY","metodo":"GET"}而不是期望的{"Nome":"TONY","Metodo":"GET"}。下面给你两种可行的解决办法:

方法一:单个函数返回时指定序列化设置

直接在返回JsonResult的时候,传入自定义的序列化配置,强制保持属性原命名:

[FunctionName("json")] 
public static JsonResult json ( [HttpTrigger(AuthorizationLevel.Anonymous, new string[] { "POST", "GET", "DELETE", "PATCH", "PUT" })] HttpRequest req, TraceWriter log ) 
{ 
    // 创建序列化设置,使用默认契约解析器保持原属性名
    var jsonSettings = new Newtonsoft.Json.JsonSerializerSettings
    {
        ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver()
    };
    
    return new JsonResult(new { Nome = "TONY", Metodo = req.Method.ToString() }, jsonSettings); 
}

方法二:全局统一配置(适用于多个函数)

如果你的Functions项目是基于ASP.NET Core的,可以通过Startup类全局配置JSON序列化规则,和你之前在ASP.NET Core 2里的思路一致:

首先创建Startup.cs(如果没有的话):

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Serialization;

[assembly: FunctionsStartup(typeof(YourNamespace.Startup))]
namespace YourNamespace
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddMvc()
                .AddJsonOptions(options =>
                {
                    // 针对Newtonsoft.Json的配置(多数Azure Functions版本默认用这个)
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                    
                    // 如果你的项目用的是System.Text.Json(较新版本),则替换为:
                    // options.JsonSerializerOptions.PropertyNamingPolicy = null;
                });
        }
    }
}

原理说明

Azure Functions默认会启用camelCase的JSON命名策略,这是为了符合前端常用的JSON命名习惯,但如果你需要保持后端定义的PascalCase,就需要通过上述方式修改序列化配置,禁用自动大小写转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:16:34