-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProductsController.cs
More file actions
96 lines (87 loc) · 3.1 KB
/
ProductsController.cs
File metadata and controls
96 lines (87 loc) · 3.1 KB
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
88
89
90
91
92
93
94
95
96
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TryApi.ProductData;
using TryApi.Products;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace TryApi.Controllers
{
[Route("api/products")]
[ApiController]
[Authorize] // Защищаем весь контроллер от неавторизованных пользователей
public class ProductsController : ControllerBase
{
private readonly ApplicationDbContext _context;
// Инъекция контекста базы данных через конструктор
public ProductsController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/products
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
try
{
var products = await _context.Products.ToListAsync();
return Ok(products);
}
catch (Exception ex)
{
// Логирование ошибки
// _logger.LogError(ex, "Error occurred while getting products.");
return StatusCode(500, "Internal server error");
}
}
// GET: api/products/{id}
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(int id)
{
try
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
catch (Exception ex)
{
// Логирование ошибки
// _logger.LogError(ex, "Error occurred while getting product.");
return StatusCode(500, "Internal server error");
}
}
// POST: api/products
[HttpPost]
public async Task<ActionResult<Product>> CreateProduct([FromBody] ProductCreateDto dto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var product = new Product
{
Name = dto.Name,
Description = dto.Description,
Price = dto.Price,
Category = dto.Category,
Stock = dto.Stock
};
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
catch (Exception ex)
{
// Логирование ошибки
// _logger.LogError(ex, "Error occurred while creating product.");
return StatusCode(500, "Internal server error");
}
}
}
}