ASP.NET Core正在把PascalCase转换为camelCase

前端开发 2026-07-07

Context: 我在前端使用React构建一个单页应用(SPA),后端是基于控制器的ASP.NET Core API。

I defined the following model in ASP.NET :

namespace TodoApi.Models;

public class TodoItemDTO
{
    public  long Id { get; set; }
    public string? name { get; set; }
    public bool IsComplete { get; set; }
}

I get this error

命名规则违规:这些单词必须以大写字母开头:name。

I fixed this error by using Name instead of name, no problem.

let data = fetchDataFromBackend();

The crazy thing is that when the frontend gets data from the backend, I get it in camelCase, not in PascalCase.

使用 console.log(data),我看到如下:

[
    {
        "id": 1,
        "name": "",
        "isComplete": false
    },
    {
        "id": 2,
        "name": "item1",
        "isComplete": false
    },
    {
        "id": 3,
        "name": "get  bath",
        "isComplete": false
    }
]

Can anyone explain the reason? Why is everything turned into camelCase?

有人能解释原因吗?为什么一切都变成camelCase?

解决方案

I knew the answer: by default, ASP.NET Core uses camel case for JSON property names (e.g., minDate, maxInt). This may not match your C# model's Pascal case property names (e.g., MinDate, MaxInt).

答案其实很简单:默认情况下,ASP.NET Core对 JSON属性名使用camelCase(例如 minDatemaxInt)。这可能与C#模型中PascalCase的属性名不匹配(例如 MinDateMaxInt)。

Solution

PropertyNamingPolicy = null 设置为保留原始的C#大小写(PascalCase)。

Code example:

// For MVC Controllers
builder.Services
       .AddControllers()
       .AddJsonOptions(options =>
           {
               // Use PascalCase for property names (null = no transformation, keeps original casing)
               options.JsonSerializerOptions.PropertyNamingPolicy = null;
           });

// For Minimal APIs and OpenAPI schema generation
builder.Services
       .Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
           {
               // Use PascalCase for property names in OpenAPI schema (null = no transformation)
               options.SerializerOptions.PropertyNamingPolicy = null;
           });

Reference: https://www.mykolaaleksandrov.dev/posts/2025/12/aspnet-json-serialization-tuning/

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章