Asp.Net Web Api - ModelBinders

Pau*_*ett 14 model-binding asp.net-mvc-4 asp.net-web-api

我需要使用某种自定义模型绑定器来处理英国格式的传入日期,我已经设置了自定义模型绑定器并注册如下:

GlobalConfiguration.Configuration.BindParameter(typeof(DateTime), new DateTimeModelBinder());
Run Code Online (Sandbox Code Playgroud)

这似乎只适用于查询字符串参数,并且只有在我的参数上指定[ModelBinder]时才有效,是否有办法让所有操作都使用我的模型绑定器:

public IList<LeadsLeadRowViewModel> Get([ModelBinder]LeadsIndexViewModel inputModel)
Run Code Online (Sandbox Code Playgroud)

另外,如何将我发布的表单发送到我的Api控制器以使用我的模型绑定器?

jim*_*974 6

您可以通过实现ModelBinderProvider并将其插入服务列表来全局注册模型绑定器.

Global.asax中的示例:

GlobalConfiguration.Configuration.Services.Insert(typeof(ModelBinderProvider), 0, new Core.Api.ModelBinders.DateTimeModelBinderProvider());
Run Code Online (Sandbox Code Playgroud)

下面是演示ModelBinderProvider和ModelProvider实现的示例代码,它以文化感知方式转换DateTime参数(使用当前线程文化);

DateTimeModelBinderProvider实现:

using System;
using System.Web.Http;
using System.Web.Http.ModelBinding;
Run Code Online (Sandbox Code Playgroud)

...

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; 
    }
}
Run Code Online (Sandbox Code Playgroud)

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?);
    }
}
Run Code Online (Sandbox Code Playgroud)


Fra*_*ese 5

我认为你不需要模型粘合剂.你的方法不正确.日期的正确方法是使用客户端全球化库(如globalize库)来解析以任何语言格式化的日期并将其转换为JavaScript日期对象.然后,您可以使用浏览器JSON.stringify在json中序列化数据脚本数据结构,这应该可行.最好始终使用日期的标准格式,并使用格式化程序而不是模型装订器.如果使用C#DateTime对象的kind参数指定日期时间是以本地时间还是以UTC时间表示,则可用格式化程序也可以正确处理TimeZones .