我希望所有 JSON 响应都使用驼峰式大小写,并尝试了下面的代码,但它不起作用,并且响应仍然采用 Pascal 大小写。我也尝试将
[JsonPropertyName("myCamelCaseProperty")]
设置为覆盖,但响应仍然是 Pascal 情况。
有什么建议如何将驼峰式大小写设置为所有响应(所有属性)的默认值?
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
options.SerializerOptions.PropertyNameCaseInsensitive = false;
options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
在startup.cs中:
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
options.SerializerOptions.PropertyNameCaseInsensitive = false;
options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
然后安装
Microsoft.AspNetCore.Mvc.NewtonsoftJson
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.0" />
在上面的课程参考中使用
[JsonProperty("customName")]
public class YourModel
{
[JsonProperty("customName")]
public string CustomName { get; set; }
public string AnotherProperty { get; set; }
}