-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageController.cs
More file actions
66 lines (56 loc) · 1.93 KB
/
ImageController.cs
File metadata and controls
66 lines (56 loc) · 1.93 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
using BusinessLayer.DTOs.ImageDTOs;
using BusinessLayer.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
namespace WebAPI.Controllers;
[Route("api/[controller]")]
[ApiController]
public class ImageController : ControllerBase
{
private readonly IImageService _imageService;
private readonly IMemoryCache _memoryCache;
private readonly MemoryCacheEntryOptions _cacheEntryOptions;
public ImageController(IImageService imageService, IMemoryCache memoryCache)
{
_imageService = imageService;
_memoryCache = memoryCache;
_cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(
TimeSpan.FromSeconds(10)
);
}
[HttpGet]
public async Task<ActionResult<ResponseImageDto>> GetImageById(int id)
{
string cacheKey = $"ImageById_{id}";
if (!_memoryCache.TryGetValue(cacheKey, out ResponseImageDto? imageDto))
{
var image = await _imageService.LoadImageDataByIdAsync(id);
if (image == null)
{
return NotFound();
}
_memoryCache.Set(cacheKey, imageDto, _cacheEntryOptions);
}
return Ok(imageDto);
}
[HttpPost("upload")]
public async Task<ActionResult<ResponseImageDto>> UploadImage(IFormFile file)
{
if (file.Length == 0)
return BadRequest("Empty file provided.");
using var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream);
var image = await _imageService.SaveSingleImageAsync(memoryStream.ToArray());
return Ok(image);
}
[HttpDelete]
public async Task<ActionResult<ResponseImageDto>> DeleteImageById(int id)
{
var deletedImage = await _imageService.DeleteImageByIdAsync(id);
if (deletedImage == null)
{
return NotFound();
}
return Ok(deletedImage);
}
}