Complement [FromUri] serialization with APIController

佐手、 提交于 2019-12-22 07:57:57

问题


We have multiple API controllers accepting GET requests like so:

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

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"

After the change all [FromUri] serializations with classes containing DateTime types fail.

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?

EDIT: example as requested

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

回答1:


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());


来源:https://stackoverflow.com/questions/42020282/complement-fromuri-serialization-with-apicontroller

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