使用API​​Controller补充序列化

我们有多个API控制器接受GET请求,如下所示:

//FooController public IHttpActionResult Get([FromUri]Foo f); //BarController public IHttpActionResult Get([FromUri]Bar b); 

现在 – 我们希望(或者,被迫) 全局更改GET查询字符串中的DateTime字符串格式

 "yyyy-MM-ddTHH:mm:ss" -> "yyyy-MM-ddTHH.mm.ss" 

更改后,包含DateTime类型的类的所有[FromUri]序列化都将失败。

有没有办法补充[FromUri]序列化以接受查询字符串中的DateTime格式? 或者我们是否必须为所有API参数构建自定义序列化以支持新的DateTime字符串格式?

编辑 :请求的示例

 public class Foo { public DateTime time {get; set;} } //FooController. Let's say route is api/foo public IHttpActionResult Get([FromUri]Foo f); GET api/foo?time=2017-01-01T12.00.00 

若要在所有模型上应用所需的所有DateTime类型的行为,那么您将要为DateTime类型编写自定义绑定器并全局应用它 。

DateTime Model Binder

 public class MyDateTimeModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { if (bindingContext.ModelType != typeof(DateTime)) return false; var time = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (time == null) bindingContext.Model = default(DateTime); else bindingContext.Model = DateTime.Parse(time.AttemptedValue.Replace(".", ":")); return true; } } 

WebAPI配置

 config.BindParameter(typeof(DateTime), new MyDateTimeModelBinder());