【发布时间】:2013-03-16 15:52:48
【问题描述】:
我正在开发一个简单的网络应用程序,我需要在其中绑定所有类型的实现和特定类型的接口。我的界面只有一个这样的属性
public interface IContent {
string Id { get;set; }
}
使用此接口的通用类如下所示
public class Article : IContent {
public string Id { get;set; }
public string Heading { get;set; }
}
为了清楚起见,article 类只是实现 IContent 的众多不同类之一,因此我需要一种通用的方法来存储和更新这些类型。
所以在我的控制器中我有这样的 put 方法
public void Put(string id, [System.Web.Http.ModelBinding.ModelBinder(typeof(ContentModelBinder))] IContent value)
{
// Store the updated object in ravendb
}
和 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;
}
}
上面的代码不起作用,因为它似乎没有获取 Heading 属性,即使我使用默认模型绑定器它正确绑定了 Heading。
所以,在 BindModel 方法中,我想我需要根据 Id 从 ravendb 加载正确的对象,然后使用某种默认模型绑定器来更新复杂对象?这是我需要帮助的地方。
【问题讨论】:
-
@matt-johnson 实际上我不知道如何更新模型,但我已经用一些代码更新了我的问题,但这只是为了反复试验。
-
@MattJohnson 也许可以使用 HttpContent.ReadAsAsync
或其他东西将 json 反序列化为特定类型? -
@matt-johnson 我已经用 ReadAsAsync 更新了我的代码,但我不知道为什么这不起作用?
-
嗨 Marcus,如果您在 Json 中发送/接收数据,您是否考虑过在 Json 媒体类型格式化程序的 SerializerSettings 上使用 TypeNameHandling。此设置导致类型信息出现在正文上:示例:{"$type":"Service.Article, ModelBindingTrials","Id":"A1","Heading":"algorithms"}。您的参数/返回类型可以是此处的接口。当然,此解决方案需要在有效负载上输入类型信息,但只是检查您是否考虑过它。
标签: asp.net-mvc-4 asp.net-web-api ravendb model-binding