I am trying to implement a base REST controller in aspnetcore 1.0.1 (kind of inspired from NancyFx) and it feels like this should be something that can be achieved with such a composable framework, however, I just cant get it right. The google foo is clearly weak with me today!
I have the following base controller (obviously not fully implemented yet)...
[Route("api/[controller]")]
public abstract class RestApiController<T> : Controller
{
protected abstract Func<int, Task<T>> Get { get; }
protected abstract Func<Task<IEnumerable<T>>> List { get; }
[HttpGet()]
protected virtual async Task<IEnumerable<T>> OnList()
{
if (this.List == null)
{
this.NotFound();
}
return await this.List.Invoke();
}
[HttpGet("{id:int}")]
protected virtual async Task<T> OnGet(int id)
{
if (this.Get == null)
{
this.NotFound();
}
return await this.Get.Invoke(id);
}
}
Which is inherited by the actual controller doing the work...
public class ArticleSummariesController : RestApiController<ArticleExtension>
{
private readonly ArticleManager articleManager;
protected override Func<int, Task<ArticleExtension>> Get => null;
protected override Func<Task<IEnumerable<ArticleExtension>>> List => this.ListAll;
public ArticleSummariesController(ArticleManager articleManager)
{
this.articleManager = articleManager;
}
private async Task<IEnumerable<ArticleExtension>> ListAll()
{
return await this.articleManager.GetAllAsync();
}
}
The idea is that the base controller will be responsible for handling the actual requests but delegate responsibility to it's children to provide and manipulate the data. This is so that we can ensure REST conformance in the requests but loosely couple domain logic from the controllers into "managers" that act as a facade and take repositories and apply business logic.
The problem with the code so far is that the HttpGet() attributes on the base class do not produce routes for the child class. The controller route attribute on the base class is inherited though (as stated in the docs).