Skip to content

Instantly share code, notes, and snippets.

@fredyfx
Created December 25, 2018 11:21
Show Gist options
  • Save fredyfx/1a43082cd6c142cfee9a6c02c2fcd658 to your computer and use it in GitHub Desktop.
Save fredyfx/1a43082cd6c142cfee9a6c02c2fcd658 to your computer and use it in GitHub Desktop.
api del producto.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AdvientoCSharpDic2018.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace AdvientoCSharpDic2018.Controllers
{
[Produces("application/json")]
[Route("api/producto")]
public class ProductController : Controller
{
private readonly AdvientoContext _context;
public ProductController(AdvientoContext context)
{
_context = context;
}
//GET: api/producto
[HttpGet]
public IEnumerable<Producto> GetProducto()
{
return _context.Productos;
}
//GET: api/producto/1
[HttpGet("{id}")]
public async Task<IActionResult> GetProducto([FromRoute] int id)
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var currentProduct = await _context.Productos.SingleOrDefaultAsync(p => p.Id == id);
if(currentProduct == null)
{
return NotFound();
}
return Ok(currentProduct);
}
//POST: api/producto
[HttpPost]
public async Task<IActionResult> PostProducto([FromBody]Producto producto)
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Productos.Add(producto);
await _context.SaveChangesAsync();
return CreatedAtAction("GetProducto", new {id= producto.Id}, producto);
}
private bool ExisteProducto(int id)
{
return _context.Productos.Any(p => p.Id == id);
}
[HttpPut("{id}")]
public async Task<IActionResult> PutProducto([FromRoute] int id, [FromBody] Producto producto)
{
if(!ModelState.IsValid){
return BadRequest(ModelState);
}
if(id != producto.Id)
{
return BadRequest();
}
_context.Entry(producto).State = EntityState.Modified;
try{
await _context.SaveChangesAsync();
}
catch(DbUpdateConcurrencyException)
{
if(!ExisteProducto(id))
{
return NotFound();
}else{
throw;
}
}
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProduct([FromRoute] int id)
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var currentProduct = await _context.Productos.SingleOrDefaultAsync(p=>p.Id == id);
if(currentProduct == null)
{
return NotFound();
}
_context.Productos.Remove(currentProduct);
await _context.SaveChangesAsync();
return Ok(currentProduct);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment