我正在使用自定义IModelBinder尝试将字符串转换为NodaTime LocalDates。我LocalDateBinder
看起来是这样的:使Web API IModelBinder适用于该类型的所有实例
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
这ModelBinder的,一拉
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模型绑定,但我在茫然,我什么,我需要纠正 - 我需要一个定制活页夹供应商
对于任何人看这个,我从来没有得到这个解决。但真正的问题是我的JSON序列化设置获得反序列化NodaTime对象的方式 - 我需要重写默认的DateTime处理程序。 – 2014-10-07 03:27:00