在Web Api 2中使用自定义DateTime Binder

本文关键字:自定义 DateTime Binder Web Api | 更新日期: 2023-09-27 18:03:20

我正在尝试注册我的自定义datetime绑定器,以便我可以解析datetime以自定义格式传入API。

我试图注册我的自定义DateTimeModelBinder,但它没有被击中,调试点没有到达它,它没有触发。以下是我在global asax和WebApiConfig中尝试的不同方法。

自定义活页簿注册

  protected void Application_Start()
        {
            HttpConfiguration config = GlobalConfiguration.Configuration;
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
            config.BindParameter(typeof(DateTime), new DateTimeModelBinder());
            config.BindParameter(typeof(DateTime?), new DateTimeModelBinder());
            //ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());
        GlobalConfiguration.Configuration.Services.Add(typeof(ModelBinderProvider), new DateTimeModelBinderProvider());

        GlobalConfiguration.Configure(WebApiConfig.Register);
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

Web Api Action

 [Route("")]
        public DataActionResponse PostEvent(EventBindingModel model)
        {
            return _eventService
                    .Create(model, CompanyId, UserId)
                    .CreateDataActionResponseSuccess();
        }

DateTimeModelBinder.cs

 public class DateTimeModelBinder : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var dateToParse = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
            if (string.IsNullOrEmpty(dateToParse))
                return false;
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName));

            bindingContext.Model = ParseDateTime(dateToParse);
            if (bindingContext.Model != null)
                return true;

            bindingContext.ModelState.AddModelError(
                key: bindingContext.ModelName,
                errorMessage: $"Invalid date format for {bindingContext.ModelName}:{dateToParse}. Should be in 'MM/dd/yyyy' OR 'MM/dd/yyyyTHH:mm' format.");
            return false;
        }
        public DateTime? ParseDateTime(string dateToParse)
        {
            var enUs = new CultureInfo("en-US");
            foreach (var format in SellutionConstants.Globals.BindingDateTimeFormat)
            {
                DateTime validDate;
                if (DateTime.TryParseExact(
                    s: dateToParse,
                    format: format,
                    provider: enUs,
                    style: DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces,
                    result: out validDate))
                {
                    return validDate;
                }
            }
            return null;
        }
    }

EventBindingModel.cs

   public class EventBindingModel
    {
        public int? EventId { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }

在Web Api 2中使用自定义DateTime Binder

尝试使用SimpleModelBinderProvider class

var provider = new SimpleModelBinderProvider(typeof(DateTime), new DateTimeModelBinder());
config.Services.Insert(typeof(ModelBinderProvider), 0, provider);