【问题标题】:Why is Request.Content.ReadAsAsync case insensitive?为什么 Request.Content.ReadAsAsync 不区分大小写?
【发布时间】:2015-05-22 07:28:53
【问题描述】:

假设我有从客户端发送的 json 有效负载,如下所示

{"Number": 2, "number": 4}

在服务器端,我有这个模型类。

public class Arg
{
    public int Number { get; set; }
}

payload 在我的控制器中反序列化,如下所示:

Request.Content.ReadAsAsync<Arg>();

为什么Arg.Number == 4?如何使ReadAsAsync 区分大小写?

【问题讨论】:

    标签: c# asp.net json asp.net-mvc json.net


    【解决方案1】:

    通过 Json.NET 完成反序列化。我正在深入研究过程并最终得到下一个代码:

    public JsonProperty GetClosestMatchProperty(string propertyName)
    {
        JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal);
        if (property == null)
            property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase);
    
        return property;
    }
    

    如您所见,如果它无法使用String.Ordinal 比较器获取属性,它将尝试String.OrdinalIgnoreCase,这就是它覆盖您的值的原因。

    对于名称,我只看到一种添加虚拟属性来捕获此值的解决方案:

    public class Arg
    {
        [JsonProperty("Number")]
        public int Number { get; set; }
    
        [JsonProperty("number")]
        public int SmallNumber { get; set; }
    }
    

    【讨论】:

      【解决方案2】:

      您需要在自定义反序列化器中添加一个新属性

      public class Arg
      {
          public int Number { get; set; }
          public int number { get; set; }
      }
      

      使用 newtonsoft 测试

      试图将你的类定义为不起作用

      public class Arg
      {
          [JsonProperty("Number")]
          public int Number { get; set; }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-14
        • 2011-11-17
        • 2018-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多