首页 > 解决方案 > 请求/响应将在我不知情/不知情的情况下转换为不同的命名约定

问题描述

首先我写的有点笼统,如果您需要更多信息,请告诉我!

在前端发送/接收时,我的 C#-Class 看起来像这样:

    public class Recipe : ICRUD
    {       
        public Guid ID { get; set; }
        public Guid UnitID { get; set; }
        public string Title { get; set; }
        // ... plus Lists ...
    }

[后端 => 前端]

后端

 [HttpGet("Recipe/[action]")]
 public async Task<JsonResult> GetRecipes(ServerRequest filter)

前端

   getRecipes(filter: ServerRequest) {
        return this._http.get(this.myAppUrl + 'Recipe/GetRecipes' + '?' + this.toQueryString(filter))
            .pipe(map((res: Recipe[]) => { return res; }));
    }

我正在查看我的网络流量并(某事)更改了模型:

ID => id
UnitID => unitId 
// ... plus Lists ...

所以我也改变了我的(前端,打字稿)模型:

export class Recipe {
    id: string;
    unitId: string;
    title: string; 
}

现在终于有了一个稳定的状态,我想将数据发送回服务器。

下一个问题:

[前端 => 后端]

前端

createRecipe(recipe: Recipe) {
        return this._http.post(this.myAppUrl + 'Recipe/CreateRecipe', recipe)
            .pipe(map(res => { return res; })); 

后端

[HttpPost("Recipe/[action]")]
public async Task<HttpResponseMessage> CreateRecipe([FromBody]Recipe recipe)

你猜怎么着 ?

ModelState无效,因为他不见了UnitID,是的,因为它是这样写的unitId

他期待大写字母(... UnitID..),但我正在发送unitId,然后UnitIDnull(至少这是我的解释)?

我该怎么办 ?

标签: c#jsonangulartypescriptasp.net-core

解决方案


在您不知情的情况下转换数据的“事物”是 JSON 序列化程序。在 ASP.NET Core 中,默认的 JSON 序列化程序会将帕斯卡大小写的 C# 类型转换为驼峰大小写的 JSON。例如,给定这个 C# 类

class Recipe
{
    public Guid ID { get; set; }
    public Guid UnitID { get; set; }
}

一个实例将被转换为此 JSON:

{
    "id": "...",
    "unitID": "..."
}

将 JSON 绑定到 C# 类时会发生相反的过程。注意两次出现的“id”是如何不同的。

你有几个选择:

  • 您可以使用映射到驼峰式大小写的默认 JSON 序列化程序,并调整您的前端代码以匹配由此产生的 JSON。
  • 您可以稍作改动:在 C# 中将“ID”更改为“Id”。这将不那么令人困惑,因为您的 JSON 属性将是idand unitId
  • [JsonProperty]使用(使用 Json.NET 时)或[JsonPropertyName](使用 时)等属性装饰 C# 类上的属性System.Text.Json,以完全控制它们在 JSON 中的命名方式。
  • 您可以将 JSON 序列化程序配置为不转换为驼峰式大小写。JSON 属性名称将与 C# 属性名称匹配。如何配置 JSON 序列化程序取决于您使用的 ASP.NET Core 版本。这在 ASP.NET Core 3 中进行了更改,其中 Json.NET 被替换为System.Text.Json.

如果您使用的是 ASP.NET Core MVC 2.1,您可以配置以下中使用的 Json.NET 序列化程序Startup.ConfigureServices

services.AddMvc()
    .AddJsonOptions(options => {
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
        // Other changes to options.SerializerSettings ...
    });

在这里,我将合同解析器设置回默认值,而不是驼峰式版本 ( CamelCasePropertyNamesContractResolver)。


推荐阅读