1
votes

I have some dates that come in a weird format (dd.MM.YYYY). This is something how the business wants it displayed. So, I need a custom model binder to read this date. I had this solution working fine, but when I switched over to using OWIN, then it stopped working. Here is my code right now:

My OWIN startup file:


    public void Configuration(IAppBuilder app)
    {
      var config = new HttpConfiguration();
      config.BindParameter(typeof(DateTime?), new DateTimeWebApiBinder());
      config.BindParameter(typeof(DateTime), new DateTimeWebApiBinder());  
      app.UseWebApi(config);
    }

Custom Model Binder


    public class DateTimeWebApiBinder : IModelBinder
    {
      public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
      {
        var incomingDate = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (bindingContext.ModelType == typeof(DateTime) && string.IsNullOrEmpty(incomingDate.AttemptedValue)) 
        { 
          return false; 
        }
        DateTime parsedDate;
        if (DateTime.TryParseExact(incomingDate.AttemptedValue, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
        {
          bindingContext.Model = parsedDate;
          return true;
        }
        return false;
      }
    }

What is happening, is the custom model binder is not triggering. I suspect it has something to do with the OWIN setup.

2
Please consider starting your question with a description of what you are trying to achieve and what is not going as expected. Reader want some context on what they are reading before being thrown into code examination.Kolban

2 Answers

1
votes

you can try:

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterWebApiModelBinderProvider();
builder.RegisterType<DateTimeWebApiBinder>().AsModelBinderForTypes(typeof(DateTime));


var resolver = new AutofacWebApiDependencyResolver(builder.Build());

var config = new HttpConfiguration
{
   DependencyResolver = resolver
};
app.UseWebApi(config);
0
votes

According to this article, you should put [ModelBinder(typeof(DateTimeWebApiBinder))] on the parameter of your controller.