我正在尋找處理WebApi中的繼承類型的模型綁定,我真正想要做的是處理綁定使用默認模型綁定(除了選擇類型的地方它無法這樣做),但我錯過了一些基本的東西。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調用?
您是否找到了解決辦法? – iuristona 2015-03-10 19:31:38