Custom Model Binder inheriting from DefaultModelBinder

前端 未结 2 715
迷失自我
迷失自我 2020-12-08 08:21

I\'m attempting to build a custom model binder for MVC 4 that will inherit from DefaultModelBinder. I\'d like it to intercept any interfaces at any bin

相关标签:
2条回答
  • 2020-12-08 09:13

    With MVC 4 it is easy to override the messages, if that is all you might need in a custom model binder:

        protected void Application_Start(object sender, EventArgs e)
        {
            //set mvc default messages, or language specifc
            ClientDataTypeModelValidatorProvider.ResourceClassKey = "ValidationMessages";
            DefaultModelBinder.ResourceClassKey = "ValidationMessages";
        }
    

    Then create resource file named ValidationMessages with entries like this:

    NAME: FieldMustBeDate 
    VALUE: The field {0} must be a date. 
    NAME: FieldMustBeNumeric 
    VALUE: The field {0} must be a number
    

    .

    We did this for a compliance failure. Our security scan did not like that a javascript injection would come back and appear in the Validation Messages and execute. By using this implementation we are overriding the default messages which return the user provided value.

    0 讨论(0)
  • 2020-12-08 09:19

    This article showed me that I was over-complicating the model binder. The following code works:

    public class InterfaceModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType.IsInterface)
            {
                Type desiredType = Type.GetType(
                    EncryptionService.Decrypt(
                        (string)bindingContext.ValueProvider.GetValue("AssemblyQualifiedName").ConvertTo(typeof(string))));
                bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, desiredType);
            }
    
            return base.BindModel(controllerContext, bindingContext);
        }
    }
    
    0 讨论(0)
提交回复
热议问题