Skip to content

Instantly share code, notes, and snippets.

@DamianEdwards
Created August 2, 2016 04:07
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save DamianEdwards/eb4f54eff9ef2464e67503b813d7c5d7 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication21.Data;
using WebApplication21.Models;
namespace WebApplication21.Controllers
{
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly ProductsDbContext _db;
public ProductsController(ProductsDbContext db)
{
_db = db;
}
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var product = _db.Products.SingleOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
[HttpGet]
public List<Product> GetAll() => _db.Products.ToList();
[HttpPost]
public IActionResult Create([FromBody] Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_db.Add(product);
_db.SaveChanges();
return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
}
[HttpPut]
public IActionResult Update([FromBody] Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_db.Update(product);
_db.SaveChanges();
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var product = Get(id);
if (product == null)
{
return NotFound();
}
_db.Remove(product);
_db.SaveChanges();
return NoContent();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment