我需要使用某种类型的自定义模型绑定器来始终处理UK格式的传入日期,我已经设置了一个自定义模型绑定器,并注册如下:
GlobalConfiguration.Configuration.BindParameter(typeof(DateTime), new DateTimeModelBinder());这似乎只适用于查询字符串参数,并且只有当我在参数上指定ModelBinder时才有效,是否有方法使所有操作都使用我的模型绑定器:
public IList<LeadsLeadRowViewModel> Get([ModelBinder]LeadsIndexViewModel inputModel)另外,我如何让我发布的表单到我的Api控制器来使用我的模型活页夹?
发布于 2012-09-10 07:33:23
我想你不需要模型活页夹。你的方法是不正确的。处理日期的正确方法是使用客户端全球化库(如globalize library )来解析任何语言格式的日期,并将其转换为JavaScript date对象。然后,您可以使用浏览器JSON.stringify在JSON中序列化数据脚本数据结构,这应该是可行的。最好始终使用标准的日期格式,并使用格式化程序而不是模型绑定器。如果您使用C# DateTime对象的TimeZones参数来指定日期时间是以本地时间表示还是以UTC时间表示,则可用的格式化程序也可以正确处理kind。
发布于 2013-02-22 00:28:24
您可以通过实现ModelBinderProvider并将其插入到服务列表中来全局注册模型绑定器。
Global.asax中的示例用法:
GlobalConfiguration.Configuration.Services.Insert(typeof(ModelBinderProvider), 0, new Core.Api.ModelBinders.DateTimeModelBinderProvider());下面的示例代码演示了一个ModelBinderProvider和一个ModelProvider实现,它们以文化感知的方式转换DateTime参数(使用当前的线程区域性);
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?);
}
}发布于 2014-12-03 04:57:16
Attribute routing似乎与模型绑定冲突。如果您使用属性路由,您可以将global.asax配置封装到单个GlobalConfiguration.Config调用中,以避免初始化问题:
GlobalConfiguration.Configure(config =>
{
config.BindParameter(typeof(DateTime), new DateTimeModelBinder());
config.MapHttpAttributeRoutes();
}(如果与bug #1165相关,这个问题可能会在即将发布的ASP.NET 5中修复。)
https://stackoverflow.com/questions/12246254
复制相似问题