64 lines
1.7 KiB
C#
64 lines
1.7 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Api.Models;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
namespace Api.Controllers
|
|
{
|
|
[ApiController]
|
|
// [Authorize]
|
|
[Route("api/[controller]")]
|
|
public class ProductController : ControllerBase
|
|
{
|
|
private readonly AppDbContext _context;
|
|
|
|
public ProductController(AppDbContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
// GET: api/Product
|
|
[HttpGet]
|
|
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
|
|
{
|
|
return await _context.Products.ToListAsync();
|
|
}
|
|
|
|
// POST: api/Product
|
|
[HttpPost]
|
|
public async Task<ActionResult<Product>> PostProduct([FromBody] Product product)
|
|
{
|
|
_context.Products.Add(product);
|
|
await _context.SaveChangesAsync();
|
|
return CreatedAtAction(nameof(GetProducts), new { id = product.Id }, product);
|
|
}
|
|
|
|
// PUT: api/Product/{id}
|
|
[HttpPut("{id}")]
|
|
public async Task<IActionResult> PutProduct(int id, [FromBody] Product product)
|
|
{
|
|
if (id != product.Id)
|
|
{
|
|
return BadRequest();
|
|
}
|
|
_context.Entry(product).State = EntityState.Modified;
|
|
try
|
|
{
|
|
await _context.SaveChangesAsync();
|
|
}
|
|
catch (DbUpdateConcurrencyException)
|
|
{
|
|
if (!await _context.Products.AnyAsync(e => e.Id == id))
|
|
{
|
|
return NotFound();
|
|
}
|
|
else
|
|
{
|
|
throw;
|
|
}
|
|
}
|
|
return NoContent();
|
|
}
|
|
}
|
|
}
|