【发布时间】:2020-09-14 15:41:45
【问题描述】:
所以我有一个 WebAPI 控制器,其操作将接口作为参数,例如:
[HttpPost]
public IFoo RunBar(IBar parameters)
{
//...
}
当然,这不会按原样运行,因为它不知道如何将IBar 反序列化为具体类,因此parameters 始终是null。
我有一个转换器来处理这个问题,它被称为ConcreteTypeConverter<Bar,IBar>,它基本上只是将任何IBar 反序列化为具体类Bar,如果我在全球范围内注册它,我可以使它工作,例如:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new ConcreteTypeConverter<Bar,IBar>())
但这是 a) 乏味和 b) 如果我注册一大堆这些,可能不会对性能产生影响吗?那么有没有更简单的方法呢?有没有办法将转换器附加到 action 以仅用于 this 特定操作?也许在概念上等同于:
[JsonConverter(typeof(ConcreteTypeConverter<Bar, IBar >))]
[HttpPost]
public IFoo RunBar(IBar parameters)
{
//...
}
这显然不起作用,因为您可以在方法上使用JsonConverterAttribute。
如果这样的东西尚不存在,您必须在哪里连接到管道以拦截对操作的调用并在转换器尝试反序列化参数之前插入转换器?
【问题讨论】:
-
这样做有充分的理由吗?好像您在这里与 WebAPI 作斗争。为什么不简单地使用具体类(无论如何实现接口)作为操作方法的参数,这样默认绑定器就可以发挥它的魔力?
标签: c# asp.net-web-api json.net