-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProductController.cs
87 lines (75 loc) · 2.13 KB
/
ProductController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Shop.Data;
using Shop.Models;
[Route("products")]
public class ProductController : ControllerBase
{
[HttpGet]
[Route("")]
[AllowAnonymous]
public async Task<ActionResult<List<Product>>> Get(
[FromServices] DataContext context
)
{
var products = await context
.Products
.Include(x => x.Category)
.AsNoTracking()
.ToListAsync();
return products;
}
[HttpGet]
[Route("{id:int}")]
[AllowAnonymous]
public async Task<ActionResult<Product>> GetByID(int id,
[FromServices] DataContext context)
{
var product = await context
.Products
.Include(x => x.Category)
.AsNoTracking()
.FirstOrDefaultAsync(x => x.Id == id);
return product;
}
[HttpGet] //products/categories/1
[Route("categories/{id:int}")]
[AllowAnonymous]
public async Task<ActionResult<List<Product>>> GetByCategory(int id,
[FromServices] DataContext context)
{
var products = await context
.Products
.Include(x => x.Category)
.AsNoTracking()
.Where(x => x.CategoryId == id)
.ToListAsync();
return products;
}
[HttpPost]
[Route("")]
[Authorize(Roles = "employee")]
public async Task<ActionResult<List<Product>>> Post(
[FromBody]Product model,
[FromServices] DataContext context)
{
if(!ModelState.IsValid)
return BadRequest(ModelState);
try
{
//Adicionando a categoria no BD
context.Products.Add(model);
//salvando as alterações de forma assincrona.
await context.SaveChangesAsync();
return Ok(model);
}
catch
{
return BadRequest(new { message = "Não foi possível criar o produto." });
}
}
}