我是 Azure Functions 的新手,正在尝试将 .NET Core API 转换为 Azure Functions。我面临的问题是如何全局设置响应命名约定(JSON)。默认情况下,它是CamelCase
但我想用PascalCase
,我在互联网上找到的所有解决方案都是修改每个函数/端点中的响应。我想在全球范围内进行设置
我已经添加了Startup.cs
配置 DI。以下是我尝试配置响应 JSON 命名约定的尝试:
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddMvcCore().AddJsonOptions(m =>
{
m.JsonSerializerOptions.PropertyNamingPolicy = null;
});
builder.Services.Configure<JsonSerializerSettings>(m =>
{
m.ContractResolver = new DefaultContractResolver();
});
builder.Services.Configure<JsonSerializerOptions>(m =>
{
m.DictionaryKeyPolicy = null;
m.PropertyNamingPolicy = null;
});
builder.Services.Configure<JsonOptions>(m =>
{
m.JsonSerializerOptions.DictionaryKeyPolicy = null;
m.JsonSerializerOptions.PropertyNamingPolicy = null;
});
.....
}
函数示例(两者返回相同的响应,即驼峰命名法):
[FunctionName(nameof(Get))]
public async Task<IEnumerable<AppComponentViewModel>> Get([HttpTrigger(AuthorizationLevel.Function, "get", Route = "AppComponent/Get")] HttpRequest request)
{
var appComponents = await _appComponentRepository.GetAll();
return ToList(appComponents);
}
[FunctionName(nameof(Get))]
public async Task<ActionResult<IEnumerable<AppComponentViewModel>>> Get([HttpTrigger(AuthorizationLevel.Function, "get", Route = "AppComponent/Get")] HttpRequest request)
{
var appComponents = await _appComponentRepository.GetAll();
return Ok(ToList(appComponents));
}
默认情况下,Azure 函数主机使用“Newtonsoft.Json”,而不是 .net core 3+ 中引入的“System.Text,Json”。您可以使用下面的代码Startup.cs
覆盖 MVC Json 序列化行为,这将保留您的属性名称大小写与实体类中的大小写相同。在下面的代码中它不会转换为camelCase
不再,但同时也不会显式转换为PascalCase
。它与 C# 对象相同。
注意:添加nugetMicrosoft.AspNetCore.Mvc.NewtonsoftJson
版本 3.1.*(至少在 Function 开始支持 .net 5 之前不是最新的 5)。
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddMvc()
.AddNewtonsoftJson(o =>
{
o.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
}
如果您想专门强制所有内容都采用 Pascal 大小写,而不管 C# 对象中的大小写是什么,那么您可以创建您的NamingStrategy
类具有该逻辑并分配它。
public class MyNamingStrategy : NamingStrategy
{
protected override string ResolvePropertyName(string s)
{
// add logic to force name to desired casing
}
}
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddMvc()
.AddNewtonsoftJson(o =>
{
o.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new MyNamingStrategy()
};
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)