ASP.NET 3.0。在 POST 请求中无法将以秒为单位的日期从 JSON 转换为 System.Date

ASP.NET 3.0. Date in seconds cannot be converted from JSON to System.Date within POST request

我想用简单的请求测试我的 POST 端点,其正文中包含 JSON。

我有一个 ASP.NET Core 3.0 项目,其中包含一个控制器和一个端点。我主要创建了空 ASP.NET 核心项目。 然后我创建了一个简单的控制器来处理 POST 请求。


    [ApiController]
    [Route("api/[controller]")]
    public class UpdateController : Controller
    {
        // POST api/update
        [HttpPost]
        public async Task<IActionResult> Post(Update update)
        {
            return Ok();
        }
    }

Update class 是 Telegram.Bot.Types

的类型

当我尝试使用正文中的以下数据测试我的 POST 操作方法时:


    {
    "update_id":10000,
    "message":{
      "date":1441645532,
      "chat":{
         "last_name":"Test Lastname",
         "id":1111111,
         "first_name":"Test",
         "username":"Test"
      },
      "message_id":1365,
      "from":{
         "last_name":"Test Lastname",
         "id":1111111,
         "first_name":"Test",
         "username":"Test"
      },
      "text":"/start"
      }
    }

我收到以下错误: The JSON value could not be converted to System.DateTime. Path: $.message.date | LineNumber: 3 | BytePositionInLine: 19.

但我预计它会正常工作。

我已经在 Telegram 的存储库中检查了 Message 类型。 Message 类型属于 Update 一个作为 属性.

日期标有UnixDateTimeConverter:

    [JsonProperty(Required = Required.Always)]
    [JsonConverter(typeof(UnixDateTimeConverter))]
    public DateTime Date { get; set; }

我也尝试使用 Newtonsoft.JSON 从上面反序列化 JSON,它没有任何错误。但是通过 ASP.NET Core 3.0 项目完成它仍然有问题。

您可以尝试以下方法:

[JsonConverter(typeof(JavaScriptDateTimeConverter))]

做一个双数据注释,否则你将不得不编写自己的自定义转换器。

从 ASP.NET Core 3.0 开始,Json.NET 不再作为默认的 JSON(反)序列化器包含在内,该角色已赋予 System.Text.Json。

在很多情况下,这就足够了。尽管在所有情况下都不能使用 System.Text.Json 代替 Json.NET - 这是故意的,因为它应该是轻量级的。但是,如果 System.Text.Json 不能满足您的需求,您仍然可以在 ASP.Net Core 3.0 中使用 Json.NET。

形成 Immo Landwerth 的博客 post Try the new System.Text.Json APIs there's a section on Integration with ASP.NET Core MVC

If you’d like to switch back to the previous default of using Newtonsoft.Json, do the following:

  1. Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package.
  2. In ConfigureServices() add a call to AddNewtonsoftJson()
public void ConfigureServices(IServiceCollection services)
 {
     ...
     services.AddControllers()
+            .AddNewtonsoftJson()
     ...
 }