使用Web API和RavenDB具有继承自定义模型绑定 [英] Custom model binder with inheritance using Web API and RavenDB
问题描述
我正在开发一个简单的Web应用程序,我需要绑定各类实施和特定类型的接口。我的接口有像这样的单一属性。
I'm developing a simple web app where I need to bind all types implementing and interface of a specific type. My interface has one single property like this
public interface IContent {
string Id { get;set; }
}
使用这个接口应该是这样一个共同的类
a common class using this interface would look like this
public class Article : IContent {
public string Id { get;set; }
public string Heading { get;set; }
}
要干净这里的文章类只是实现IContent所以我为此需要存储和更新这些类型的通用的方式许多不同的类中的一个。
to be clean here the article class is just one of many different classes implementing IContent so therefor I need a generic way of storing and updating these types.
所以,在我的控制器我有这样的put方法
So in my controller I have the put method like this
public void Put(string id, [System.Web.Http.ModelBinding.ModelBinder(typeof(ContentModelBinder))] IContent value)
{
// Store the updated object in ravendb
}
和ContentBinder
and the ContentBinder
public class ContentModelBinder : System.Web.Http.ModelBinding.IModelBinder {
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
actionContext.ControllerContext.Request.Content.ReadAsAsync<Article>().ContinueWith(task =>
{
Article model = task.Result;
bindingContext.Model = model;
});
return true;
}
}
在code以上不工作,因为它似乎并没有得到镦性能的保持,即使如果我使用默认的模型绑定其绑定正确的航向。
The code above does not work because it does not seem to get hold of the Heading property even though if I use the default model binder it binds the Heading correctly.
所以,在BindModel方法我想我需要加载从ravendb基于ID正确的对象,然后更新使用某种默认的模型绑定左右的复杂对象?这是我需要一些帮助。
So, in the BindModel method I guess I need to load the correct object from ravendb based on the Id and then update the complex object using some kind of default model binder or so? This is where I need some help.
推荐答案
我用@基兰 - challa的解决方案,并添加TypeNameHandling JSON的媒体类型格式的SerializerSettings。
I used @kiran-challa solution and added TypeNameHandling on Json media type formatter's SerializerSettings.
这篇关于使用Web API和RavenDB具有继承自定义模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!