1

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?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
g_b
  • 11,728
  • 9
  • 43
  • 80
  • 4
    What purpose does an interface have in model binding? .NET can only instantiate classes, so which implementation of the interface should it use? – CodeCaster May 09 '16 at 11:01
  • @CodeCaster: In the old Web API, there are some workarounds like https://brettedotnet.wordpress.com/2014/07/16/web-api-and-interface-parameters/. I wanted to know if there is also something I can do in Web API Core. – g_b May 09 '16 at 11:11
  • You could try to write an own json input formatter... (implement `IInputFormatter` and register it in mvc options: `options.InputFormatters.Insert(0, new MyJsonInputFormatter());` – Tseng May 09 '16 at 11:20
  • 1
    Even if you find a workaround, this remains a bad practice. I agree with @CodeCaster, you shouldn't use interfaces in models. – Federico Dipuma May 09 '16 at 12:01
  • Plus it's not worth the effort. There is not much value in abstracting poco classes – Tseng May 09 '16 at 12:38

1 Answers1

0

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.

Community
  • 1
  • 1
alltej
  • 6,787
  • 10
  • 46
  • 87