カスタム IModelBinder を使用して、文字列を NodaTime LocalDates に変換しようとしています。私LocalDateBinder
はこのように見えます:
public class LocalDateBinder : IModelBinder
{
private readonly LocalDatePattern _localDatePattern = LocalDatePattern.IsoPattern;
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(LocalDate))
return false;
var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (val == null)
return false;
var rawValue = val.RawValue as string;
var result = _localDatePattern.Parse(rawValue);
if (result.Success)
bindingContext.Model = result.Value;
return result.Success;
}
}
私の WebApiConfig では、このモデルバインダーを を使用して登録しますSimpleModelBinderProvider
。
var provider = new SimpleModelBinderProvider(typeof(LocalDate), new LocalDateBinder());
config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
これは、タイプ LocalDate のパラメーターを受け取るアクションがある場合はうまく機能しますが、別のモデル内で LocalDate を使用するより複雑なアクションがある場合は、決して起動されません。例えば:
[HttpGet]
[Route("validateDates")]
public async Task<IHttpActionResult> ValidateDates(string userName, [FromUri] LocalDate beginDate, [FromUri] LocalDate endDate)
{
//works fine
}
[HttpPost]
[Route("")]
public async Task<IHttpActionResult> Create(CreateRequest createRequest)
{
//doesn't bind LocalDate properties inside createRequest (other properties are bound correctly)
//i.e., createRequest.StartDate isn't bound
}
これは、モデル バインダーを Web API に登録する方法と関係があると思いますが、何を修正する必要があるのか途方に暮れています - カスタム バインダー プロバイダーが必要ですか?