私は ASP .NET MVC 4 RC 内で Web API を使用しており、null 可能な DateTime プロパティを持つ複雑なオブジェクトを受け取るメソッドがあります。入力の値をクエリ文字列から読み取る必要があるため、次のようなものがあります。
public class MyCriteria
{
public int? ID { get; set; }
public DateTime? Date { get; set; }
}
[HttpGet]
public IEnumerable<MyResult> Search([FromUri]MyCriteria criteria)
{
// Do stuff here.
}
これは、2012 年 1 月 15 日のようなクエリ文字列で標準の日付形式を渡すとうまく機能します。
http://mysite/Search?ID=1&Date=01/15/2012
ただし、DateTime のカスタム形式 (おそらく MMddyyyy) を指定したい... 例:
http://mysite/Search?ID=1&Date=01152012
編集:
カスタム モデル バインダーを適用しようとしましたが、DateTime オブジェクトだけに適用できませんでした。私が試した ModelBinderProvider は次のようになります。
public class DateTimeModelBinderProvider : ModelBinderProvider
{
public override IModelBinder GetBinder(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(DateTime) || bindingContext.ModelType == typeof(DateTime?))
{
return new DateTimeModelBinder();
}
return null;
}
}
// In the Global.asax
GlobalConfiguration.Configuration.Services.Add(typeof(ModelBinderProvider), new DateTimeModelBinderProvider());
新しいモデル バインダー プロバイダーが作成されますが、GetBinder
1 回だけ呼び出されます (モデル内の各プロパティではなく、複雑なモデル パラメーターに対して)。DateTimeModelBinder
これは理にかなっていますが、非 DateTime プロパティのデフォルト バインディングを使用しながら、DateTime プロパティにmy を使用する方法を見つけたいと思います。デフォルトをオーバーライドして、ModelBinder
各プロパティのバインド方法を指定する方法はありますか?
ありがとう!!!