简体   繁体   English

ASP.NET Core Web API - 当类的成员是接口时,参数绑定不起作用

[英]ASP.NET Core Web API - Parameter binding does not work when member of a class is an Interface

I have a method in my Web API Controller:我的 Web API 控制器中有一个方法:

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

I am able to invoke the method but the parameter is always null.我能够调用该方法,但参数始终为空。 Registration class is defined as:注册类定义为:

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; }
}

It seems the Student property of Registration being an interface is what's causing this since when I try to replace it with a concrete type, it binds just fine.似乎 Registration 的 Student 属性是一个接口是造成这种情况的原因,因为当我尝试用具体类型替换它时,它绑定得很好。

How do I make this bind when using an interface?使用接口时如何进行绑定? Also, on my original Web API, I am accepting a parameter of type Registration.此外,在我原来的 Web API 上,我接受了一个注册类型的参数。 Is it possible also to make this as an Interface (IRegistration) and still bind?是否也可以将其作为接口(IRegistration)并仍然绑定?

It is possible but you have to do some extra coding.这是可能的,但你必须做一些额外的编码。 An example is implemeted here:这里实现了一个例子:

ASP.NET Web API Operation with interfaces instead concrete class 使用接口而不是具体类的 ASP.NET Web API 操作

You probably don't want to do this extra code.您可能不想执行此额外代码。 It can get buggy.它可能会出现故障。 You can create POCOs/DTOs and use Automapper to map your business domain models to your POCOs/DTOs.您可以创建 POCO/DTO 并使用 Automapper 将您的业务领域模型映射到您的 POCO/DTO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM