【发布时间】:2013-08-21 20:32:45
【问题描述】:
我正在尝试将控制器操作绑定到接口,但仍保持默认绑定行为。
public class CoolClass : ISomeInterface
{
public DoSomething {get;set;} // ISomeInterface
}
public class DosomethingController : ApiController
{
public HttpResponseMessage Post(ISomeInterface model)
{
// do something with model which should be an instance of CoolClass
}
}
我的服务的消费者对 CoolClass 一无所知,所以让他们在传递的 Json 中添加“$type”在我看来是一种黑客行为。我希望能够在服务中处理它。如果我将 CoolClass 指定为操作参数,它就可以正常工作。
编辑:所以我在这里找到了我的问题的部分解决方案Dependency injection for ASP.NET Web API action method parameters,但有一个后续问题。该解决方案不解析接口属性。请参阅下面的示例。
IConcreteClass 将被解析,但 ISubtype 不会。
public class SubConcreteClass : ISubtype
{
// properties
}
public class ConcreteClass : IConcreteClass
{
public ISubtype Subtype {get;set;}
}
一旦媒体格式化程序发现它可以解析 IConcreteClass 中的类型,它就会读取整个流。所以我猜没有机会解析接口成员。
【问题讨论】:
-
另一种选择,请查看我对类似问题的回答here。
标签: c# asp.net-mvc asp.net-web-api parameterbinding