ASP.NET Web API - ModelBinders

前端 未结 4 403
渐次进展
渐次进展 2021-01-08 01:13

I need to use a custom modelbinder of some kind to always treat incoming dates in UK format, i have setup a custom model binder and registered like so:

Globa         


        
4条回答
  •  长发绾君心
    2021-01-08 02:09

    You can register a model binder globally by implementing a ModelBinderProvider and inserting it into the list of services.

    Example use in Global.asax:

    GlobalConfiguration.Configuration.Services.Insert(typeof(ModelBinderProvider), 0, new Core.Api.ModelBinders.DateTimeModelBinderProvider());
    

    Below is example code demonstrating a ModelBinderProvider and a ModelProvider implemenation that converts DateTime arguments in a culture aware manner (using the current threads culture);

    DateTimeModelBinderProvider implementation:

    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 implementation:

    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?);
        }
    }
    

提交回复
热议问题