您可以通过实施ModelBinderProvider并将其插入到服务列表中来全局注册模型联编程序。在Global.asax中
实施例使用:
GlobalConfiguration.Configuration.Services.Insert(typeof(ModelBinderProvider), 0, new Core.Api.ModelBinders.DateTimeModelBinderProvider());
下面是示例代码演示一个ModelBinderProvider以及变换器,在培养知道地日期时间参数的ModelProvider实行(使用当前线程培养);
DateTimeModelBinderProvider实现:
using System;
using System.Web.Http;
using System.Web.Http.ModelBinding;
...
public class DateTimeModelBinderProvider : ModelBinderProvider
{
readonly DateTimeModelBinder binder = new DateTimeModelBinder();
public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
{
if (DateTimeModelBinder.CanBindType(modelType))
{
return binder;
}
return null;
}
}
DateTimeModelBinder实现:
public class DateTimeModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
ValidateBindingContext(bindingContext);
if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName) ||
!CanBindType(bindingContext.ModelType))
{
return false;
}
bindingContext.Model = bindingContext.ValueProvider
.GetValue(bindingContext.ModelName)
.ConvertTo(bindingContext.ModelType, Thread.CurrentThread.CurrentCulture);
bindingContext.ValidationNode.ValidateAllProperties = true;
return true;
}
private static void ValidateBindingContext(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}
if (bindingContext.ModelMetadata == null)
{
throw new ArgumentException("ModelMetadata cannot be null", "bindingContext");
}
}
public static bool CanBindType(Type modelType)
{
return modelType == typeof(DateTime) || modelType == typeof(DateTime?);
}
}
在发布之前,我如何将客户端的所有日期格式化为iso格式,我是否需要在每个日期字段的每个帖子前手动执行此操作?似乎有点乏味和重复? –
绝对不是!您可以通过传递一个识别日期并将其转换为适当字符串的函数来定制浏览器的JSON.stringify函数。一旦你完成了这个,你可以调用JSON.stringify来转换所有js模型在日期中使用正确的格式 –
实际上,所有主浏览器JSON.stringify函数的默认行为应该是将日期转换为iso格式。所以你不必做任何事情:) –