要实现ASP.NET Core中基于通用存储库接口的通用控制器,你可以按照以下步骤进行操作:
public interface IRepository
{
IEnumerable GetAll();
T GetById(int id);
void Add(T entity);
void Update(T entity);
void Delete(T entity);
}
ControllerBase
并实现了通用存储库接口。[Route("api/[controller]")]
[ApiController]
public abstract class GenericController : ControllerBase where T : class
{
private readonly IRepository _repository;
public GenericController(IRepository repository)
{
_repository = repository;
}
[HttpGet]
public ActionResult> GetAll()
{
var entities = _repository.GetAll();
return Ok(entities);
}
[HttpGet("{id}")]
public ActionResult GetById(int id)
{
var entity = _repository.GetById(id);
if (entity == null)
{
return NotFound();
}
return Ok(entity);
}
[HttpPost]
public ActionResult Add([FromBody] T entity)
{
_repository.Add(entity);
return CreatedAtAction(nameof(GetById), new { id = entity.Id }, entity);
}
[HttpPut("{id}")]
public ActionResult Update(int id, [FromBody] T entity)
{
var existingEntity = _repository.GetById(id);
if (existingEntity == null)
{
return NotFound();
}
_repository.Update(entity);
return NoContent();
}
[HttpDelete("{id}")]
public ActionResult Delete(int id)
{
var entity = _repository.GetById(id);
if (entity == null)
{
return NotFound();
}
_repository.Delete(entity);
return NoContent();
}
}
public class UserController : GenericController
{
public UserController(IRepository repository) : base(repository)
{
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped, UserRepository>();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 省略其他配置
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
这样,你就可以使用UserController
来处理与用户相关的HTTP请求,并且可以通过依赖注入来注入具体的用户存储库实现。