ASP.NET Core 6 驼峰式情况下的最小 API 响应 JSON

问题描述 投票:0回答:2

我希望所有 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();
json asp.net-core-6.0 camelcasing
2个回答
0
投票

默认情况下.Net 6 以驼峰命名法给出响应。这是我的模型和响应的屏幕截图。

回应:


0
投票

在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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.