Why the controller response are setting model field names into lower case?

限于喜欢 提交于 2021-02-17 03:18:04

问题


In my .NET Core project, in the response of all controllers, the object fields are coming in lower case in the first one or two letters of the field name:

{
  "iD_PARAM": "foo",
  "cD_PROM": "bar",
  "txT_OFFICER": "lorem",
  "cN_NEW_PARAM": "fubá",
  "iD_SITUATION": "XX",
  "iD_NEW_USER": "ipsun",
}

It's strange, because the model has all fields in UPPER case:

public partial class MyModel {
   public long ID_PARAM { get; set; }
   public long CD_PROM { get; set; }
   public string TXT_OFFICER { get; set; }
   public int CN_NEW_PARAM { get; set; }
   public int ID_SITUATION { get; set; }     
   public int ID_NEW_USER { get; set; }  
}

For more detail, this is the controller where I set the values and the response:

[HttpPost("receive")]

    public async Task<IActionResult> Get()
    {
      try
      {
        MyModel newParam = new MyModel ();

        newParam.ID_PARAM = "foo";
        newParam.CD_PROM = "foo";
        newParam.TXT_OFFICER = "lorem";
        newParam.CN_NEW_PARAM = "fubá";
        newParam.ID_SITUATION = "XX";
        newParam.ID_NEW_USER = "ipsun";

        return Ok(newParam);
      }
      catch (Exception ex)
      {
        return BadRequest(ex);
      }
    }

回答1:


Assuming you are using Newtonsoft Json, if you want your Json properties to be uppercase, try decorating your Model with JsonProperty like this to prevent the Serializer try to infer the property name :

public partial class MyModel {
  [JsonProperty("ID_PARAM")]
  public long ID_PARAM { get; set; }
  [JsonProperty("CD_PROM")]
  public long CD_PROM { get; set; }
  [JsonProperty("TXT_OFFICER")]
  public string TXT_OFFICER { get; set; }
  [JsonProperty("CN_NEW_PARAM")]
  public int CN_NEW_PARAM { get; set; }
  [JsonProperty("ID_SITUATION")]
  public int ID_SITUATION { get; set; }     
  [JsonProperty("ID_NEW_USER")]
  public int ID_NEW_USER { get; set; }  
}



回答2:


You should change the ContractResolver, just add below code in startup ConfigurSservices

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

Refer to Lowercase property names from Json() in .Net core



来源:https://stackoverflow.com/questions/58193412/why-the-controller-response-are-setting-model-field-names-into-lower-case

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!