/
nicteres
/
Lab1
Обзор
Документация
Войти
/
nicteres
/
Lab1
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
123
API_Lab_1/Controllers/v0/ShelfController.cs
82 строки
3 KB
Matthew
Добавьте файлы проекта.
18 окт 2025, 18:03
18 окт 2025, 18:03
79e10ad
Код
Авторство
О чём код?
using API_Lab_1.src; using API_Lab_1.src.Interface; using API_Lab_1.src.Models; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using System.Net.Http; namespace API_Lab_1.Controllers.v0 { [Route("api/v{version:apiVersion}/[controller]")] [EnableRateLimiting("fixedLimiter")] [ApiVersion("1.0")] [ApiController] public class ShelfController(IShelfService shelfService, IHttpClientFactory httpClientFactory) : ControllerBase { [Authorize(Roles = "user, admin")] [HttpGet("GetAll")] public async Task<ActionResult> GetAllBooks() { await LogAsync("GetAllBooks called"); var shelf = await shelfService.GetAllBooks(); if (shelf == null) return BadRequest("No books exists"); return Ok(shelf); } [Authorize(Roles = "user, admin")] [HttpGet("GetByID")] public async Task<ActionResult> GetBook(int id) { await LogAsync("GetByID called"); var book = await shelfService.GetBookById(id); if (book == null) return BadRequest("No book exists"); return Ok(book); } [Authorize(Roles = "user, admin")] [HttpGet("GetByRange")] public async Task<ActionResult> GetRange(int id_start, int id_end) { await LogAsync("GetByRange called"); var books = await shelfService.GetRange(id_start, id_end); if (books == null) return BadRequest("Out of range"); return Ok(books); } [Authorize(Roles = "user, admin")] [HttpPost("Create")] public async Task<ActionResult> CreateBook(ShelfRequest shelf, [FromHeader(Name = "Idempotency-Key")] string? idempotencyKey) { await LogAsync("CreateBook called"); var book = await shelfService.CreateBook(shelf); return Ok(book); } private async Task LogAsync(string message) { var client = httpClientFactory.CreateClient(); var url = $"{Request.Scheme}://{Request.Host}/api/v1/Internal"; var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("input", message) }); var response = await client.PostAsync(url, content); if (!response.IsSuccessStatusCode) { // Optionally log or handle the error var error = await response.Content.ReadAsStringAsync(); // You can log error here if needed } } } }