API请求中不支持接口类型的反序列化



我得到这个错误消息系统。NotSupportedException:接口类型的反序列化是不支持的。

同时调用API,该API按照如下方式接收请求。

例子
[HttpPost]
public IActionResult AddSomeData(MyClass MyClass)
{
return Ok();
}

public class MyClass : MyInterface
{
return Ok();
}

public interface MyInterface 
{
public string SomeOtherProperties { get; set; }
public MyInterface Property { get; set; } //Or reference of any other interface
}

我已经尝试了在线给出的例子,如创建具体类和添加属性的属性。但这并没有帮助。

作为解决方案,我已经删除了公共MyInterface属性{get;设置;}并添加了公共MyClass属性{get;设置;}

有更好的解决方案吗?

对接口进行反序列化的问题是会丢失信息

public class MyClass : MyInterface
{
public string SomeOtherProperties { get; set; }
public MyInterface Property { get; set; }
public string importantString { get; set; } = "Don't lose me please";
}
public interface MyInterface
{
string SomeOtherProperties { get; set; }
MyInterface Property { get; set; }
}

以上面的例子为例,试图反序列化到接口将涉及告诉反序列化器只知道接口上的属性-而最终用户提供的任何其他字段将被完全删除。最重要的是,你可以在具体类上使用方法来支持需要存在的接口属性。

如果你需要API来支持一个接口的多个实现,你可以使用一些涉及反射的选项,但问题是你为什么首先需要这个接口?API应该清楚地定义需要由用户提供的内容,将其抽象为需要由某个神秘的具体类实现的接口似乎是一个坏主意。

编辑:如果所有你需要的是共享信息,没有什么花哨的-你可以使用MyInterface作为一个标准类

public class MyClass : MyInterface
{
public string nonImportantString { get; set; } = "lose me";
}
public class MyInterface
{
public  string SomeOtherProperties { get; set; }
public  MyInterface Property { get; set; }
}

这样做你的api是干净的,你可以反序列化好