0
私はカスタムdatetimeバインダーを登録しようとしていますので、datetimeをカスタム形式のAPIに変換することができます。Web Api 2のカスタムDateTimeバインダーの使用
私は自分のカスタムDateTimeModelBinder
を登録しようとしましたが、ヒットせず、デバッグポイントが来ず、トリガーしません。以下は、グローバル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をアクション
[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; }
}