【问题标题】:Webapi controller changes property names to lower caseWebapi 控制器将属性名称更改为小写
【发布时间】:2021-02-12 06:11:36
【问题描述】:

我有这样的课:

public class Creature
{
    public string Town { get; set; }
    public string Name { get; set; }
    public int Level { get; set; }
    public bool Upgrade { get; set; }
    public int Attack { get; set; }
    public int Defence { get; set; }
    public int MinDamage { get; set; }
    public int MaxDamage { get; set; }
    public int Speed { get; set; }
    public int Hp { get; set; }
    public int Cost { get; set; }
}

public class CreaturesList
{
    public List<Creature> Creatures { get; set; }
}

 public class ReadCreatures : IReadCreatures
    {
        public Creature GetCreature(string name)
        {
            var result = GetData(); 
            return result.Creatures.Where(w => w.Name.ToLower().Equals(name.ToLower())).FirstOrDefault();
        }

        protected CreaturesList GetData()  => JsonSerializer.Deserialize<CreaturesList>(heroes3wiki.Properties.Resources.Creatures);
    }
}

和控制器:

public class CreaturesController : ControllerBase
{

    private readonly ILogger<CreaturesController> _logger;
    private readonly IReadCreatures _getCreatures;

    public CreaturesController(ILogger<CreaturesController> logger , IReadCreatures getCreatures)
    {
        _logger = logger;
        _getCreatures = getCreatures;
    }

    [HttpGet]
    public IEnumerable<Creature> Get() => _getCreatures.GetCreatures();

    [HttpGet("{name}")]
    public Creature Get(string name) => _getCreatures.GetCreature(name);

}

如您所见,我在 Creature 类的第一个大写字母中拥有所有属性。但是当我调用这个端点时,我会收到如下数据:

{"town":"Castle","name":"Pikeman","level":1,"upgrade":false,"attack":4,"defence":5,"minDamage":1,"maxDamage":3,"speed":4,"hp":10,"cost":60}

任何人都可以解释一下它应该是这样还是我在某处有错误?

【问题讨论】:

  • 因为这就是 ASP.NET Core 的 JsonOutputFormatter 写入 JSON 值的方式。但是你为什么在乎呢?
  • @IanKemp 因为在我的 angular.io 应用程序的前端我有界面,我也有大写的属性
  • 非标准 JSON。 JSON 是属性的驼峰式,C# 是驼峰式。因此,为什么 ASP.NET Core 从 C# 样式转换为 JSON 样式。
  • @IanKemp JSON 实际上并不关心属性的大小写。或者如果你使用snake_case 或任何你想要的,只要它是一个有效的标识符。
  • JSON 序列化器和反序列化器非常关心大小写。而且我没有说它无效,我说它是非标准的。

标签: c# asp.net-core-webapi


【解决方案1】:

Asp.Net Core 改变了默认行为(我认为是在 2.x 和 3.x 之间)。

如果您想保留属性的名称(并且不更改大小写),则需要将 PropertyNamingPolicy 设置为 null

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddControllers()
        .AddJsonOptions(options => {
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
        });
}

来自JsonSerializerOptions.PropertyNamingPolicy 上的文档:

属性命名策略,或null 保持属性名称不变。

【讨论】:

  • 很确定您需要将其设置为 JsonNamingPolicy.CamelCase - null 是默认的驼峰式,IIRC。
  • @IanKemp 查看the docsPropertyNamingPolicy 的值是“属性命名策略,或者为 null 以保持属性名称不变。”
  • @IanKemp 不,你错了。它必须是null,以便属性不变。 CamalCase 仍然是小写。
猜你喜欢
  • 1970-01-01
  • 2017-06-24
  • 1970-01-01
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
  • 2019-02-26
相关资源
最近更新 更多