Untitled
Chicky
plain_text
2 years ago
3.0 kB
14
Indexable
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using YourApp.Models;
namespace YourApp.Controllers
{
public class ProductsController : ApiController
{
private readonly YourDbContext _context;
public ProductsController()
{
_context = new YourDbContext();
}
// GET: api/Products
[HttpGet]
public async Task<IHttpActionResult> GetProducts()
{
var products = await _context.Products.ToListAsync();
return Ok(products);
}
// GET: api/Products/5
[HttpGet]
public async Task<IHttpActionResult> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
// POST: api/Products
[HttpPost]
public async Task<IHttpActionResult> AddProduct(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = product.ProductId }, product);
}
// PUT: api/Products/5
[HttpPut]
public async Task<IHttpActionResult> UpdateProduct(int id, Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != product.ProductId)
{
return BadRequest();
}
_context.Entry(product).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(System.Net.HttpStatusCode.NoContent);
}
// DELETE: api/Products/5
[HttpDelete]
public async Task<IHttpActionResult> DeleteProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
_context.Products.Remove(product);
await _context.SaveChangesAsync();
return Ok(product);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
private bool ProductExists(int id)
{
return _context.Products.Any(e => e.ProductId == id);
}
}
}
Editor is loading...
Leave a Comment