简体   繁体   中英

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:

[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.

How do I make this bind when using an interface? Also, on my original Web API, I am accepting a parameter of type Registration. Is it possible also to make this as an Interface (IRegistration) and still bind?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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