0

I am building a REST service that serves up data either from my database or a mock location.

[Route("[controller]")]
public class ProjectController : ControllerBase

I have an interface that defines the properties I actually need in the client.

public interface IProject : IProduction
{
    string Title { get; set; }
}

And two implementations of the interface, a stripped down mock object:

public class MockProject : ProductionBase, IProject
{
    public string Title { get; set; }
}

And a fancy one that has data we don't all want to let out to the public interfaces.

public class DBProject : ProductionDBBase, IDBReadable, IProject
{
    public string ExternalProjectTitle { get; set; }

    public DateTime ModifyDate { get; set; }

    public string RootDirectory { get; set; }

    public string Title { get; set; }
}

So in my controller I have a GET function,

    [HttpGet]
    public ActionResult<IEnumerable<IProject>> GetProjects()
    {
        Enumerable<IProject> projects = ...
        return projects;
    }

but it's serializing all the properties of DBProject, not just the properties of IProject. Can I change this behavior without making a copy constructor in MockProject and converting all the objects before serialization? Or decorating every property I don't want serialized with attributes?

Denise Skidmore
  • 2,286
  • 22
  • 51
  • IMHO converting into a new object having only the needed properties is the best and safest method. That's the reason my controller methods never return an interface (except `IEnumerable<>` for collections). Instead it would return a `ProjectResponse` (or for collections like in your case an `IEnumerable`). The copy itself can be simplified by using AutoMapper. – Oliver Oct 21 '21 at 06:00
  • In code review we're finding other reasons to return a simplified transfer object class rather than an interface, so that's the route I'm going to go. – Denise Skidmore Oct 23 '21 at 23:33

0 Answers0