Custom Model Binder inheriting from DefaultModelBinder

前端 未结 2 722
迷失自我
迷失自我 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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);
        }
    }
    

提交回复
热议问题