Web Api 序列化程序将对象序列化为驼峰式 json

Web Api serializer serialize object to camel-case json

请考虑此代码:

var ResultMaster = new Master()
{
    Id = Result.Id,
    CityCode = Result.CityCode,
    Desc = Result.Desc,
    EmployeeId = Result.EmployeeId,
    IsDelete = Result.IsDelete,
    LastChange = Result.LastChange,
    StateCode = Result.StateCode,
};

return Ok(ResultMaster);

当我调用 Web API 方法时,我得到了驼峰式 json:

'{"id":1,"cityCode":"001","desc":null,"employeeId":36648,"isDelete":false,"lastChange":"2021-11-25","stateCode":"01"}'

所以我可以使用

反序列化它
System.Text.Json.JsonSerializer.Deserialize<T>

public static async Task<T?> GetObjectFromResponse<T>(this Task<HttpResponseMessage> responseMessage)
{
      var Response = await responseMessage;
      string StringContent = await Response.Content.ReadAsStringAsync();
      var Obj = JsonSerializer.Deserialize<T>(StringContent);
      //var Obj = JsonSerializer.Deserialize<T>("{\"Id\":1,\"CityCode\":\"001\",\"Desc\":null,\"EmployeeId\":36648,\"IsDelete\":false,\"LastChange\":\"2021-11-25\",\"StateCode\":\"01\"}");
      return Obj;
}

我在我的 Blazor WASM 中调用上面的方法是这样的:

var Master = await _httpClient.GetAsync($"/api/Ques/GetObject?id={id}").GetObjectFromResponse<MasterDTO>();
return Master;

我清空 Master 对象(不为空)。但是,如果我将 属性 名称更改为 Pascal-case(上面的注释代码),那么我会得到正确的对象。

如何为我的 API 序列化程序设置配置保留属性名称?

谢谢

只需在 ConfigureServices 部分添加此代码:

services.AddControllers()
        .AddJsonOptions(options => 
        {
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
        });