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

问题描述 投票:0回答:1

我收到此错误消息:

System.NotSupportedException:不支持接口类型的反序列化。

在调用接受请求的 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
}

我尝试过在线给出的示例,例如创建具体类并在属性上添加属性,但它没有帮助。

作为解决方法,我删除了

public MyInterface Property { get; set; }
并添加了
public MyClass Property { get; set; }

有更好的解决方案吗?

c# .net .net-core interface
1个回答
1
投票

反序列化到接口的问题是你会丢失信息

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 是干净的,你可以很好地反序列化

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.