Skip to content

Instantly share code, notes, and snippets.

@dgwaldo
Created November 12, 2014 18:24
Show Gist options
  • Save dgwaldo/6f2ddbbee3432f69666d to your computer and use it in GitHub Desktop.
Save dgwaldo/6f2ddbbee3432f69666d to your computer and use it in GitHub Desktop.
Web API - [FromUri] example
public class QueryRequest
{
public QueryRequest()
{
Query = null;
Page = 1;
PageSize = 10;
}
public string Query { get; set; }
public int Page { get; set; }
public int PageSize { get; set; }
}
public async Task<PagedResults<T>> GetAsync(int page, int pageSize, string query = null)
{
HttpResponseMessage response = await Client.GetAsync(BaseRoute() + String.Format("?page={0}&pageSize={1}&query={2}", page, pageSize, query));
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<PagedResults<T>>(new List<MediaTypeFormatter> { JsonFormatter });
}
public async Task<T> GetAsync(int id)
{
HttpResponseMessage response = await Client.GetAsync(string.Format(BaseRoute() + "{0}", id));
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<T>(new List<MediaTypeFormatter> { JsonFormatter });
}
/// <summary>Gets paged fluid data from the server.</summary>
/// <param name="q">Query parameters, including page, pageSize and query parameter for search.</param>
/// <returns>Fluid information, including the total entity count, and the paged results.</returns>
public async Task<IHttpActionResult> GetAsync([FromUri] QueryRequest q)
{
var query = q.Query == null ? await TfContext.Fluids.OrderBy(b => b.DateUpdated).ToListAsync()
: await TfContext.Fluids.Where(x => x.Name.Contains(q.Query))
.OrderBy(b => b.DateUpdated).ToListAsync();
var currentPage = query.Skip(q.PageSize * (q.Page - 1)).Take(q.PageSize);
var totalCount = query.Count;
var totalPages = (int)Math.Ceiling((double)totalCount / q.PageSize);
return Ok(new PagedResults<FluidModel>
{
Links = CreateLinks("Fluids", q.Page, q.PageSize, totalCount, totalPages),
TotalCount = query.Count,
TotalPages = totalPages,
Results = currentPage.Select(w => ModelFactory.Create(w)).ToList()
});
}
/// <summary>Gets one fluid entity.</summary>
/// <param name="id">Id of fluid to retrieve</param>
/// <returns>Requested entity of 'Id'</returns>
public async Task<IHttpActionResult> GetAsync(int id)
{
var query = await TfContext.Fluids.FirstOrDefaultAsync(x => x.Id == id);
if (query == null) return NotFound();
var model = ModelFactory.Create(query);
return Ok(model);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment