【问题标题】:ASP.NET Core Web API - Parameter binding does not work when member of a class is an InterfaceASP.NET Core Web API - 当类的成员是接口时,参数绑定不起作用
【发布时间】:2016-09-03 23:32:58
【问题描述】:

我的 Web API 控制器中有一个方法:

[HttpPost]
public void Post([FromBody]Registration registration)
{
    // omitted
}

我可以调用该方法,但参数始终为空。注册类定义为:

public class Registration
{
    public int Id { get; set; }
    public IStudent Student { get; set; }
}

public interface IStudent
{
    string FirstName { get; set; }
    string LastName { get; set; }
}

public class Student : IStudent
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

似乎 Registration 的 Student 属性是一个接口是造成这种情况的原因,因为当我尝试用具体类型替换它时,它绑定得很好。

使用接口时如何进行此绑定?另外,在我原来的 Web API 上,我接受了一个注册类型的参数。是否也可以将其作为接口 (IRegistration) 并仍然绑定?

【问题讨论】:

  • 接口在模型绑定中有什么用途? .NET 只能实例化类,那么应该使用哪个接口实现呢?
  • @CodeCaster:在旧的 Web API 中,有一些解决方法,例如 brettedotnet.wordpress.com/2014/07/16/…。我想知道在 Web API Core 中是否还有我可以做的事情。
  • 您可以尝试编写自己的 json 输入格式化程序...(实现 IInputFormatter 并将其注册到 mvc 选项中:options.InputFormatters.Insert(0, new MyJsonInputFormatter());
  • 即使您找到了解决方法,这仍然是一种不好的做法。我同意@CodeCaster,你不应该在模型中使用接口。
  • 另外,这不值得。抽象 poco 类没有多大价值

标签: c# asp.net-core asp.net-core-webapi


【解决方案1】:

这是可能的,但您必须进行一些额外的编码。这里实现了一个例子:

ASP.NET Web API Operation with interfaces instead concrete class

您可能不想执行此额外代码。它可能会出错。您可以创建 POCO/DTO 并使用 Automapper 将您的业务领域模型映射到您的 POCO/DTO。

【讨论】:

    猜你喜欢
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    相关资源
    最近更新 更多