4

WebAPI v4 エンドポイントのモデルの 1 つに type のフィールドがありますNodaTime.Instant。モデルの検証では、これが失敗したことが常に報告され ( Model.IsValid == false)、エラー メッセージ "Unexpected token parsing Instant. Expected String, got Date." が表示されます。これは明らかにNodaTimeからのものです。

実際、要求メッセージはInstantISO-8601 日付を含む文字列として を渡します。そのため、DateTimeNodaTime が取得する前のある時点で BCL に解析される必要があります。と を使用してみOffsetDateTimeましLocalDateTimeたが、いずれの場合も同様のエラーが発生しました。

それで、私はここで何をすべきですか?以外のものを渡す必要がありInstantますか? このエラーを引き起こさない解析または検証を処理する他の方法はありますか?

以下に最小限の再現を含めました。次のようなリクエストボディで POST すると失敗するはずです{"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; }
    }
}
4

1 に答える 1