问题描述
我们有多个API控制器接受GET请求,如下所示:
We have multiple API controllers accepting GET requests like so:
//FooController
public IHttpActionResult Get([FromUri]Foo f);
//BarController
public IHttpActionResult Get([FromUri]Bar b);
现在 - 我们希望(或者,被迫)在GET查询字符串中更改DateTime字符串格式全球
Now - we would like (or, are forced) to change DateTime string format within GET query string globally
"yyyy-MM-ddTHH:mm:ss" -> "yyyy-MM-ddTHH.mm.ss"
更改后所有 [FromUri]
包含 DateTime
类的类序列化失败。
After the change all [FromUri]
serializations with classes containing DateTime
types fail.
有没有办法补充 [FromUri]
序列化以接受查询字符串中的DateTime格式?或者我们是否必须为所有API参数构建自定义序列化以支持新的DateTime字符串格式?
Is there a way to complement [FromUri]
serialization to accept the DateTime format in query string? Or do we have to build custom serialization for all API parameters to support new DateTime string format?
编辑:按要求提供的示例
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类型的行为,那么您需要编写。
To apply this behavior that you want across all DateTime types on all models, then you'll want to write a custom binder for the DateTime type and apply it globally.
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());
这篇关于使用APIController补充[FromUri]序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!