Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- namespace persistence_examples.Controllers
- {
- public class Receipt
- {
- public int Id { get; set; }
- public string Title { get; set; }
- public decimal Total { get; set; }
- public List<ReceiptItem> Items { get; set; }
- }
- public class ReceiptItem
- {
- public int ItemNo { get; set; }
- public string ProductName { get; set; }
- public int Quantity { get; set; }
- public decimal Price { get; set; }
- public decimal Value { get; set; }
- }
- [Route("api/[controller]")]
- [ApiController]
- public class ReceiptController : ControllerBase
- {
- private static List<Receipt> _receipts = new List<Receipt>();
- public ReceiptController()
- {
- // If there are no receipts, generate some for testing
- if (!_receipts.Any())
- {
- var totals = new decimal[] { 10.99M, 11.99M, 29.99M, 99.99M };
- var titles = new string[] { "Monthly Subscription", "Monthly Subscription - Family", "Quarterly Subscription", "Annual Subscription" };
- var currentId = 1;
- var rnd = new Random();
- for (var i = 0; i < 100; i++)
- {
- var rndIdx = rnd.Next(totals.Length);
- _receipts.Add(new Receipt
- {
- Id = currentId,
- Total = totals[rndIdx],
- Title = titles[rndIdx],
- });
- currentId++;
- }
- }
- }
- [HttpGet()]
- public ActionResult<Receipt> GetAll()
- {
- return Ok(_receipts);
- }
- [HttpGet("{id}")]
- public ActionResult<Receipt> Get(int id)
- {
- var retVal = _receipts.FirstOrDefault(x => x.Id == id);
- if(retVal == null)
- return NotFound();
- return Ok(retVal);
- }
- [HttpGet("[action]")]
- public ActionResult<Receipt> Paged(int page, int size, string orderBy, string direction)
- {
- IEnumerable<Receipt> ordered;
- // Ordering
- if (string.Compare(orderBy, "id", true) == 0)
- {
- ordered = _receipts.OrderBy(x => x.Id);
- }
- else if (string.Compare(orderBy, "title", true) == 0)
- {
- ordered = _receipts.OrderBy(x => x.Title);
- }
- else if (string.Compare(orderBy, "total", true) == 0)
- {
- ordered = _receipts.OrderBy(x => x.Total);
- }
- else
- {
- // default: order by Id
- ordered = _receipts.OrderBy(x => x.Id);
- }
- // For descending order we just reverse it
- if (string.Compare(direction, "desc", true) == 0)
- {
- ordered = ordered.Reverse();
- }
- // Now we can page the correctly ordered items
- var retVal = ordered.Skip(page * size).Take(size);
- return Ok(retVal);
- }
- [HttpGet("[action]")]
- public ActionResult<Receipt> Filtered(string filter)
- {
- var retVal =
- _receipts.Where(x =>
- x.Title.Contains(filter, StringComparison.InvariantCultureIgnoreCase));
- return Ok(retVal);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement