2014-10-01 63 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

相关问题