Supplement [FromUri] serialization using APIController

We have several API controllers that accept GET requests as follows:

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

Now - we would like (or, forcibly) change the format of the DateTime string in the GET request string globally

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

After the change, all serializations [FromUri]with classes containing types DateTimefail.

Is there a way to complement serialization [FromUri]to accept the DateTime format in the query string? Or do we need to create custom serialization for all API parameters to support the new DateTime string format?

EDIT : example on request

public class Foo {
 public DateTime time {get; set;}
}

//FooController. Let say route is api/foo
public IHttpActionResult Get([FromUri]Foo f);

GET api/foo?time=2017-01-01T12.00.00
+4
1

DateTime , DateTime .

DateTime

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

Source: https://habr.com/ru/post/1668710/


All Articles