【发布时间】:2013-03-09 01:37:45
【问题描述】:
我希望在 WebApi 中处理继承类型的模型绑定,而我真正想做的是使用默认模型绑定来处理绑定(除了选择无法这样做的类型) ,但我缺少一些基本的东西。
所以说我有类型:
public abstract class ModuleVM
{
public abstract ModuleType ModuleType { get; }
}
public class ConcreteVM : ModuleVM
{
}
使用 MVC 控制器,我会做这样的事情:
public class ModuleMvcBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
if (modelType == typeof(ModuleVM))
{
// Just hardcoding the type for simplicity
Type instantiationType = typeof(ConcreteVM);
var obj = Activator.CreateInstance(instantiationType);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, instantiationType);
bindingContext.ModelMetadata.Model = obj;
return obj;
}
return base.CreateModel(controllerContext, bindingContext, modelType);
}
}
[AttributeUsage( AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Struct | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ModuleMvcBinderAttribute : CustomModelBinderAttribute
{
public override IModelBinder GetBinder()
{
return new ModuleMvcBinder();
}
}
然后使用控制器上的属性,一切都很好,我正在利用 DefaultModelBinder 进行实际工作,我基本上只是提供正确的对象实例化。
那么我该如何为 WebApi 版本做同样的事情呢?
如果我使用自定义模型绑定器(例如Error implementing a Custom Model Binder in Asp.Net Web API),我的问题是(我相信)在 BindModel 方法中,一旦实例化对象,我还没有找到使用“标准”http 绑定的好方法.正如其他帖子中所建议的那样,我可以专门针对 JSON (Deserialising Json to derived types in Asp.Net Web API) 或 XML (Getting my Custom Model bound to my POST controller) 执行此操作,但在我看来,这违背了这一点,因为 web api 应该将其分开,而且是 - 它只是没有知道如何确定类型。 (所有具体类型自然都处理得很好。)
我是否忽略了一些明显的事情,我应该在实例化对象后将 BindModel 调用定向到?
【问题讨论】:
-
你找到解决办法了吗?
标签: asp.net-mvc-4 asp.net-web-api