Exemplo n.º 1
0
        public Tuple <string[], string[]> Get()
        {
            HttpActionContext actionContext = new HttpActionContext
            {
                ControllerContext = this.ControllerContext
            };
            ModelMetadataProvider metadataProvider = this.Configuration.Services.GetModelMetadataProvider();
            ModelMetadata         metadata         = metadataProvider.GetMetadataForType(null, typeof(DemoModel));
            IValueProvider        valueProvider    = new CompositeValueProviderFactory(this.Configuration.Services.GetValueProviderFactories()).GetValueProvider(actionContext);
            ModelBindingContext   bindingContext   = new ModelBindingContext
            {
                ModelMetadata = metadata,
                ValueProvider = valueProvider,
                ModelState    = actionContext.ModelState
            };

            actionContext.Bind(bindingContext);

            //验证之前的错误消息
            string[] errorMessages1 = actionContext.ModelState.SelectMany(
                item => item.Value.Errors.Select(
                    error => error.ErrorMessage)).ToArray();

            //验证之前的错误消息
            bindingContext.ValidationNode.Validate(actionContext);
            string[] errorMessages2 = actionContext.ModelState.SelectMany(
                item => item.Value.Errors.Select(
                    error => error.ErrorMessage)).ToArray();
            return(new Tuple <string[], string[]>(errorMessages1, errorMessages2));
        }
        private ModelBindingContext GetModelBindingContext(
            ModelMetadataProvider metadataProvider,
            HttpActionContext actionContext
            )
        {
            string name = Descriptor.ParameterName;
            Type   type = Descriptor.ParameterType;

            string prefix = Descriptor.Prefix;

            IValueProvider vp = CompositeValueProviderFactory.GetValueProvider(
                actionContext,
                _valueProviderFactories
                );

            ModelBindingContext ctx = new ModelBindingContext()
            {
                ModelName             = prefix ?? name,
                FallbackToEmptyPrefix = prefix == null, // only fall back if prefix not specified
                ModelMetadata         = metadataProvider.GetMetadataForType(null, type),
                ModelState            = actionContext.ModelState,
                ValueProvider         = vp
            };

            return(ctx);
        }