我的 WebAPI v4 端点的模型之一有一个 type 字段NodaTime.Instant
。模型验证总是报告失败 ( Model.IsValid == false
),并带有错误消息“Unexpected token parsing Instant. Expected String, got Date.” 这显然来自NodaTime。
请求消息实际上确实Instant
作为包含 ISO-8601 日期的字符串传递,因此必须DateTime
在 NodaTime 获取它之前的某个时间点将其解析为 BCL。我尝试使用OffsetDateTime
and LocalDateTime
,但在每种情况下都遇到了类似的错误。
那么我应该在这里做什么?我应该传递除 a 以外的东西Instant
吗?是否有其他方法来处理不会导致此错误的解析或验证?
我在下面包含了一个最小的复制。如果您使用类似的请求正文向其发布,它应该会失败{"SomeInstant":"2013-08-13T17:51:22.1705292Z"}
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using NodaTime;
namespace TestProject.Controllers
{
/** Assume that we called GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Bcl) in Global.asax.cs **/
public class NodaTimeController : ApiController
{
public Instant Post(TestModel m)
{
//ModelState.IsValid is always false due to error parsing the Instant field
if (!ModelState.IsValid)
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
}
return m.SomeInstant;
}
}
public class TestModel
{
public Instant SomeInstant { get; set; }
}
}