c# - Web API 将输入转换为随机 int

标签 c# post asp.net-web-api json.net

不确定该主题是否是对此问题的最佳描述,但我遇到了一个不寻常的问题,我有一个 Web API 操作和一个请求字段,并且由于某些奇怪的原因该值被操纵。根据输入,这会被 Web API 或什至由 JSON.NET 等其他东西转换/翻译吗?

应该提到这是一个全新的项目,除了在 Visual Studio 中创建新的 Web API 项目时默认添加的内容外,没有其他引用。

public class TestController : ApiController
{
    public void Post(Foo request)
    {
    }
}
public class Foo
{
    public string Blah { get; set; }
}

使用休息客户端,我使用以下请求点击操作:

{
  "Blah": 43443333222211111117
}

调试时,Blah 的值被转换为 "6549845074792007885"。我不明白它是如何以及为什么这样做的?它尊重的任何其他值(value)。例如:

{
  "Blah": 53443333222211111117
}

这绝对没问题,但数字更大。

谢谢,DS。

最佳答案

更新

This bug has been fixed and is scheduled to be included in the next release .

原始答案

正如所暗示的那样,这是 JSON.NET 中的一个错误,但它并不像乍看起来那么简单。

5.0.4 之前的版本适用于这两个测试用例。之后的任何事情似乎都失败了,但仅针对第一个奇怪的测试用例。我已经浏览了一些 JSON.NET 代码以尝试查看这种混淆发生的位置,但目前无法弄清楚为什么会这样,我需要做更多的挖掘。

2147483647                      Int Max
4444333322221111                Valid Credit Card Number Format
9223372036854775807             Int 64 Max
43443333222211111117            Dodgy Number greater than Int 64 hence overflow
53443333222211111117            Larger than above and Int 64, but works oddly.
1.7976931348623157E+308.        Decimal max

Why 53443333222211111117 works is very odd. JSON.NET seems to have a 1025 character buffer set aside that contains a load of jibberish for my test cases, eventually the number is read incorrectly. I'll check this out further and raise an issue with JSON.NET.

If you use a decimal for the property this will work in all cases where the leading number is not zero, but this isn't a solution. For the short term, use version 5.0.3.

Take this example program to demonstrate the problem.

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Sending in: \n43443333222211111117");
            var largeBrokenNumber = JsonConvert.DeserializeObject<Foo>("{\"Blah\": 43443333222211111117 }");
            Console.WriteLine(largeBrokenNumber.Blah);

            Console.WriteLine();

            Console.WriteLine("Sending in: \n53443333222211111117");
            var largeOddWorkingNumber = JsonConvert.DeserializeObject<Foo>("{\"Blah\": 53443333222211111117 }");
            Console.WriteLine(largeOddWorkingNumber.Blah);
        }
    }

    public class Foo
    {
        public string Blah { get; set; }
    }

关于c# - Web API 将输入转换为随机 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30863216/

相关文章:

c# - 删除条款中的NOT-Linq-To-SQL

javascript - 为什么在解码 URI 编码的 JSON 字符串时会收到错误 "unexpected end of string while parsing JSON string"?

javascript - 对丢弃的 http 连接进行重复处理

c# - 在 ASP.NET Identity GetRolesAsync 中使用异步等待丢失 HttpContext

c# - 有没有一种快速的方法可以将 DataGridView 的所有列设置为不可见?

c# - 使属性彼此不兼容?

c# - 获取页面上特定类型的所有 Web 控件

node.js - 如何在nodejs中调试request.post

php - 使用 JQuery 从 post() 接收响应

c# - 异常 : The given filter must implement one or more of the following filter interfaces when implementing custom filter in WebAPI 2