Skip to content

Instantly share code, notes, and snippets.

@pedrovasconcellos
Last active March 27, 2019 12:21
Show Gist options
  • Save pedrovasconcellos/407f7e9fe80d191e0bdd7b8f5e8b1381 to your computer and use it in GitHub Desktop.
Save pedrovasconcellos/407f7e9fe80d191e0bdd7b8f5e8b1381 to your computer and use it in GitHub Desktop.
Example: Car Controller with pagination in C# ASP.NET Core
using AutoMapper;
using Vasconcellos.WebAPI.Entity;
using Vasconcellos.WebAPI.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Vasconcellos.WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CarWithPaginationController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly ILogger<CarWithPaginationController> _logger;
private readonly IMapper _mapper;
/// <summary>
/// Returns the car through a Query String
/// </summary>
/// <param name="name"></param>
/// <param name="ageInitial"></param>
/// <param name="ageFinal"></param>
/// <param name="description"></param>
/// <param name="active"></param>
/// <param name="page"></param>
/// <param name="rows"></param>
/// <response code="200">Ok. Curso encontrado</response>
/// <response code="500">Erro interno do servidor.</response>
[HttpGet()]
[ProducesResponseType(typeof(IList<CarModel>), 200)]
[ProducesResponseType(500)]
public async Task<ActionResult<IList<CarModel>>> Get (string name, short? ageInitial, short? ageFinal, string description, bool? active, int? page, int? rows )
{
IQueryable<Car> query = this._context.Car.AsQueryable();
if (!string.IsNullOrEmpty(name))
query = query.Where(x => x.Name.Contains(name, StringComparison.OrdinalIgnoreCase));
if (ageInitial != null)
query = query.Where(x => x.Age >= ageInitial);
if (ageFinal != null)
query = query.Where(x => x.Age <= ageFinal);
if (!string.IsNullOrEmpty(description))
query = query.Where(x => x.Description.Contains(description, StringComparison.OrdinalIgnoreCase));
if (active != null)
query = query.Where(x => x.Active == active);
else
query = query.Where(x => x.Active);
IList<Car> entity;
if (page != null && page > 0 && rows != null && rows > 0)
{
entity = query.Skip((int)(rows * (page - 1))).Take((int)rows).ToList();
}
else
{
entity = query.ToList();
}
Request.HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "X-Total-Count");
Request.HttpContext.Response.Headers.Add("X-Total-Count", entity.Count().ToString());
return await Task.FromResult(this.Ok(_mapper.Map<List<CarModel>>(entity)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment