Web API 反序列化正在将 int 转换为字符串,我该如何防止呢?

Web API deserialization is casting an int as a string, how can I prevent it?

我有一个 API 和一个 Post 搜索操作,它接受 json 形式的正文

{
    "EventID": [
        "1234-567-890",
        "1234-567-890",
        "1234-567-890"
    ],
    "boolFlag": 0
}

并将其反序列化为 "SearchCriteria" 对象

    public class SearchCriteria
    {
        [JsonProperty(Required = Required.Always), Required]
        public string[] EventID{ get; set; }


        [JsonProperty(Required = Required.Always), Required]
        public bool boolFlag{ get; set; }    
    }

我遇到的问题是,如果我输入一个 eventID 作为整数 1234,不带引号,这在技术上是有效的 JSON。而不是使 ModelState 无效,当我进入我的控制器操作时,该 eventID 的值从 1234 变为“1234”。并在我的其余代码中继续被视为字符串。我们不希望用户能够为 eventIds 输入整数。它们必须是字符串。有没有办法将此 属性 and/or 归因于防止从 "casting" int 到字符串的反序列化?

解决方法:您可以使用方法 Int32.TryParse 将字符串转换回 int。然后你可以这样做:

public static void Main()
   {
      String[] values = { null, "160519", "9432.0", "16,667",
                          "   -322   ", "+4302", "(100);", "01FA", "11111", "1234", "1234-1234-1234" };
      foreach (var value in values) {
         int number;

         bool result = Int32.TryParse(value, out number);
         if (result == true)
         {
            Console.WriteLine("This input value is definitely not valid as it is a number.");         
         }
         else
         { 
            Console.WriteLine("Perhaps this can be a valid input value as it could not be parsed as integer.", 
                               value == null ? "<null>" : value);
         }
      }
   }

对于我使用的示例数据,我得到以下输出:

Perhaps this can be a valid input value as it could not be parsed as integer. // null
This input value is definitely not valid as it is a number. // "160519"
Perhaps this can be a valid input value as it could not be parsed as integer. // "9432.0"
Perhaps this can be a valid input value as it could not be parsed as integer. // "16,667"
This input value is definitely not valid as it is a number. // "   -322   "
This input value is definitely not valid as it is a number. // "+4302"
Perhaps this can be a valid input value as it could not be parsed as integer. // "(100);",
Perhaps this can be a valid input value as it could not be parsed as integer. // "01FA"
This input value is definitely not valid as it is a number. // "11111"
This input value is definitely not valid as it is a number. // "1234"
Perhaps this can be a valid input value as it could not be parsed as integer. // "1234-1234-1234"

有关演示,请参阅 here