Asp.net MVc tutorials

Updated : Oct 15, 2019 in Articles

Web API helper Class

In this Web Api article, we will go through web API helper class this method is Generic type methods and it will reduce the code in your application

The Basic commonly sending requests like Create, Update, Delete, Find and the Result set for these requests instead of creating different types of web API controllers for basic operations . we will use the following given API controller class ?

Create an abstract generic type class name like “ApiController<T>”

Web API helper Class
[Authorize]
[Route("api/[controller]")]
public abstract class ApiController<T> : Controller where T : class, IEntity
{
    private IApplicationRepository<T> _repository;

    public ApiController(IApplicationRepository<T> repository)
    {
        _repository = repository;
    }

    [HttpGet]
    [ValidateModel]
    public IActionResult Query()
    {
        return Ok(_repository.Get());
    }

    [HttpGet("{id}")]
    [ValidateModel]
    public IActionResult Find(Guid id)
    {
        var record = _repository.Get(id);
        if (record == null)
            return NotFound();

        return Ok(record);
    }

    [HttpPost]
    [ValidateModel]
    public async Task<IActionResult> Create([FromBody] T record)
    {
        _repository.Create(record);
        if (await _repository.SaveAsync() == 0)
            return BadRequest();

        return CreatedAtAction("Find", new { id = record.Id }, record);
    }

    [HttpPut("{id}")]
    [ValidateModel]
    public async Task<IActionResult> Update(Guid id, [FromBody] T record)
    {
        if (id != record.Id)
            return BadRequest();

        _repository.Update(record);
        if (await _repository.SaveAsync() == 0)
            return BadRequest();

        return Ok(record);
    }

    [HttpDelete("{id}")]
    [ValidateModel]
    public async Task<IActionResult> Delete(Guid id)
    {
        _repository.Delete(id);
        if (await _repository.SaveAsync() == 0)
            return BadRequest();

        return NoContent();
    }
}

Create interface class for common basic operations(create,get,update,delete,save..etc) name like IApplicationRepository<T> generic class you can add following given code

public interface IApplicationRepository<T> : IDisposable
{
    IQueryable<T> Get();
    T Get(Guid id);
    void Create(T record);
    void Update(T record);
    void Delete(Guid id);
    int Save();
    Task<int> SaveAsync();
}

The given below ApplicationRepository<T> class can inherit from IApplicationRepository<T> interface class for commonly used operations (Create, Update, Delete, Find and save, Result set) and these methods are generic types

If we want to perform the common operations by using Web APIs we will use the given below generic type methods in ApplicationRepository<T> class

public class ApplicationRepository<T> : IApplicationRepository<T> where T : class, IEntity
{
    private DbContext _context;

    public ApplicationRepository(ApplicationDbContext context)
    {
        _context = context;
    }

    public IQueryable<T> Get()
    {
        return _context.Set<T>().Where(e => !e.IsDeleted);
    }

    public T Get(Guid id)
    {
        return Get().SingleOrDefault(e => e.Id == id);
    }

    public void Create(T record)
    {
        record.CreatedOn = DateTime.Now;
        record.ModifiedOn = record.CreatedOn;
        _context.Add(record);
    }

    public void Update(T record)
    {
        record.ModifiedOn = DateTime.Now;
        _context.Set<T>().Attach(record);
        _context.Entry(record).State = EntityState.Modified;
    }

    public void Delete(Guid id)
    {
        var record = Get(id);

        if (record != null) {
            record.ModifiedOn = DateTime.Now;
            record.IsDeleted = true;
        }
    }

    public int Save()
    {
        return _context.SaveChanges();
    }

    public Task<int> SaveAsync()
    {
        return _context.SaveChangesAsync();
    }

    #region Dispose
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if(disposing)
        {
            if(_context != null)
            {
                _context.Dispose();
                _context = null;
            }
        }
    }
   #endregion
}

Like
Like Love Haha Wow Sad Angry

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x