gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:30:32 25 4
gpt4 key购买 nike

我有一个带有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com