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

标签 c# json asp.net-mvc asp.net-web-api2

我有一个带有 Post 搜索操作的 API,它接受

形式的 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 无效,当我进入我的 Controller 操作时,该 eventID 的值从 1234 变为“1234”。并在我的其余代码中继续被视为字符串。我们不希望用户能够为 eventIds 输入整数。它们必须是字符串。有没有一种方法可以赋予此属性和/或防止反序列化将 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 .

关于c# - Web API 反序列化正在将 int 转换为字符串,我该如何防止呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33922890/

相关文章:

javascript - 从 Javascript 文件访问 MVC 的模型属性

java - Genson:使用 RuntimePropertyFilter 时处理子属性

asp.net-mvc - 将 WCF 服务添加到 ASP.NET MVC 项目

c# - ajax 调用 c# mvc 发送 post 和 get

asp.net-mvc - foreach循环通过数据库表.net c#

c# - 无法从 COM 客户端实例化 DLL 中 2 个类中的 1 个

c# - 如何定义必须由类的实例实现的函数的签名?

c# - 绑定(bind)后在 GridView 中获取项目

javascript - 如何将 JSON 库格式的 JSON 日期转换为 Javascript 日期

javascript - 如何将HTML表格数据反馈到Form中进行编辑