我正在使用自定義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