Complement [FromUri] serialization with APIController

做~自己de王妃 提交于 2019-12-05 18:09:08
davidmdem

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

config.BindParameter(typeof(DateTime), new MyDateTimeModelBinder());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!