I am working on a webapi application on .net Core and I have a base controller from which all other controller derives from.
Here is the class:
public class ReadOnlyBaseController<TEntity, TEntityResource> : Controller
{
private readonly IMapper mapper;
private readonly IBaseUnitOfWork unitOfWork;
private readonly IBaseRepository<TEntity> repository;
public ReadOnlyBaseController(IBaseRepository<TEntity> repository, IBaseUnitOfWork unitOfWork,
IMapper mapper)
{
this.repository = repository;
this.unitOfWork = unitOfWork;
this.mapper = mapper;
}
[HttpGet]
[Authorize]
virtual public async Task<IActionResult> Get()
{
List<TEntity> TEntitys = await this.repository.GetTodos();
return Ok(TEntitys);
}
[HttpGet("Id")]
[Authorize]
virtual public IActionResult GeSingle(int Id)
{
TEntity tEntity = this.repository.GetSingle(Id);
TEntityResource tEntityResource = this.mapper.Map<TEntity, TEntityResource>(tEntity);
return Ok(tEntityResource);
}
}
However, some of my API endpoints do not require the Authorize attribute. So I created another base controller:
public class ReadOnlyNoOAuthBaseController<TEntity, TEntityResource> : Controller
{
private readonly IMapper mapper;
private readonly IBaseUnitOfWork unitOfWork;
private readonly IBaseRepository<TEntity> repository;
public ReadOnlyNoOAuthBaseController(IBaseRepository<TEntity> repository, IBaseUnitOfWork unitOfWork,
IMapper mapper)
{
this.repository = repository;
this.unitOfWork = unitOfWork;
this.mapper = mapper;
}
[HttpGet]
virtual public async Task<IActionResult> Get()
{
List<TEntity> TEntitys = await this.repository.GetTodos();
return Ok(TEntitys);
}
[HttpGet("Id")]
virtual public IActionResult GeSingle(int Id)
{
TEntity tEntity = this.repository.GetSingle(Id);
TEntityResource tEntityResource = this.mapper.Map<TEntity, TEntityResource>(tEntity);
return Ok(tEntityResource);
}
}
As you probably noticed, other than the [Authorize] attribute, the controllers are identical. Is there any way to make this work without the need to create a new controller?
Cheers!