Reputation: 11
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.
Upvotes: 1
Views: 570
Reputation: 47
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);
Upvotes: 1
Reputation: 1292
According to this article, you should put [ModelBinder(typeof(DateTimeWebApiBinder))]
on the parameter of your controller.
Upvotes: 0