Files
ContactsApp/Controllers/ContactController.cs
2025-12-14 18:15:23 +03:00

91 lines
2.5 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using System.Text.Json;
namespace ContactsApp
{
[ApiController]
[Route("api/contacts")]
public class ContactController(IContactRepository repository) : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable<Contact>> GetAll()
{
var contacts = repository.GetAll().ToList();
return Ok(contacts);
}
[HttpPost]
public ActionResult<Contact> Create([FromBody] Contact contact)
{
repository.AddContact(contact);
return Ok(contact);
}
[HttpGet("{id:Guid}")]
public ActionResult<Contact> GetById(Guid id)
{
var contact = repository.GetContactById(id);
if (contact == null)
return NotFound();
return Ok(contact);
}
[HttpPost("{id:Guid}")]
public ActionResult Update(Guid id, [FromBody] Contact contact)
{
repository.UpdateContact(id, contact);
return Ok();
}
[HttpDelete("{id:Guid}")]
public ActionResult Delete(Guid id)
{
var contact = repository.GetContactById(id);
if (contact == null)
return NotFound();
repository.DeleteContact(id);
return Ok();
}
[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest("Ôàéë ïóñòîé.");
using var stream = new MemoryStream();
await file.CopyToAsync(stream);
string json = System.Text.Encoding.UTF8.GetString(stream.ToArray());
try
{
repository.LoadJSON(json); // ðåïîçèòîðèé ñàì ïàðñèò JSON è îáíîâëÿåò ñïèñîê
}
catch (Exception ex)
{
return BadRequest("Îøèáêà ïðè îáðàáîòêå JSON: " + ex.Message);
}
return Ok("Êîíòàêòû óñïåøíî çàãðóæåíû.");
}
[HttpGet("download")]
public IActionResult Download()
{
string json = repository.SaveJSON(); // ðåïîçèòîðèé ôîðìèðóåò JSON ñòðîêó
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(json);
return File(
bytes,
"application/json",
"contacts.json"
);
}
}
}