2014-10-01 68 views
0

我正在使用自定義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模型綁定,但我在茫然,我什麼,我需要糾正 - 我需要一個定製活頁夾供應商

+0

對於任何人看這個,我從來沒有得到這個解決。但真正的問題是我的JSON序列化設置獲得反序列化NodaTime對象的方式 - 我需要重寫默認的DateTime處理程序。 – 2014-10-07 03:27:00

回答

1

您的CreateRequest是一種複雜的類型,它沒有定義模型聯編程序的類型轉換器。在這種情況下,Web Api將嘗試使用媒體類型的格式化程序。在使用JSON時,它會嘗試使用默認的JSON格式器,即標準配置中的Newtonsoft Json.Net。 Json.Net不知道如何處理開箱即用的Noda Time類型。

爲了Json.Net能夠處理諾達時間類型,你應該安裝NodaTime.Serialization.JsonNet,並添加像這樣到你的啓動代碼...

public void Config(IAppBuilder app) 
{ 
    var config = new HttpConfiguration(); 
    config.Formatters.JsonFormatter.SerializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); 
    app.UseWebApi(config); 
} 

在此之後,那麼你的第二個例子會按預期工作如果輸入的格式不正確,將爲false

有關Web API中參數綁定的更多信息,請參閱http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

相關問題