用 APIController 补充 [FromUri] 序列化
Complement [FromUri] serialization with APIController
我们有多个 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 类型中应用您想要的这种行为,那么您需要编写 custom binder for the DateTime type and apply it globally.
日期时间模型活页夹
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());
我们有多个 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 类型中应用您想要的这种行为,那么您需要编写 custom binder for the DateTime type and apply it globally.
日期时间模型活页夹
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());