Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to force WebAPI to strictly conform to a published interface?

The use case that I'm trying to solve is encapsulation of our domain models. For example, we have internal models that are utilized in a back-end processing that we do not want exposed to clients. One of the main reasons for this encapsulation is volatility of change as our domain objects may change more rapid than the "published" client models. Therefore we want to limit the WebApi controllers to only return "published" client models.

To do this we would need to create interfaces outside of the WebApi project that does not have references to the internal models, then utilize those interfaces on the WebAPI controllers, and finally change routing/filtering to verify that routes/methods being accessed are part of the interface.

Assembly A

public class PublishedModel
{
    public int Foo {get; set;}
    public string Bar {get; set;}
}

public interface IPublishedAPI
{
    PublishedModel GetModel(int id);
}

Assembly B

public class MyApi : ApiController, IPublishedAPI
{
    public IDomainManager _manager;

    public MyApi(IDomainManager manager)
    {
        _manager = manager;
    }

    [HttpGet]
    [Route("good/{id}")]
    public PublishedModel Good(int id)
    {
          DomainModel domainModel = _manager.GetDomainModelById(id);
          return new PublishedModel
          {
              Foo = domainModel.Foo,
              Bar = domainModel.Bar,
          }
    }

    [HttpGet]
    [Route("bad/{id}")]
    public DomainModel Bad(int id)
    {
          var domainModel = _manager.GetDomainModelById(id);
          return domainModel;
    }
}

In the above example, I would like a call to /bad/1 to return a 404 as it's a route that's not published.

Any ideas?

like image 380
Jerod Houghtelling Avatar asked Oct 30 '22 21:10

Jerod Houghtelling


1 Answers

You could create an action filter that checks to see if the mapped action is a member of the controller's inherited interface.

You could also create a filter that when manually attributed to methods you don't want exposed return the 404 Not Found response.

like image 79
Nkosi Avatar answered Nov 09 '22 23:11

Nkosi