Asp.Net_Single_Page_App/Single_Page_Anwendung/Controllers/SpeisenController.cs

108 lines
3.1 KiB
C#
Raw Normal View History

using Aps_Single_Page_Anwendung.Models;
using Aps_Single_Page_Anwendung.Repositories;
2022-05-30 09:22:35 +02:00
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace Aps_Single_Page_Anwendung.Controllers
{
// Routing für den Controller
[ApiController]
[Route("api/[controller]")]
// Muss von ControllerBase erben, sonst muss die Schnittstelle selbst implmentiert werden
public class SpeisenController : ControllerBase
{
private readonly ISpeiseRepository _repository;
2022-05-30 09:22:35 +02:00
private readonly string _path;
2022-05-30 09:22:35 +02:00
public SpeisenController(ISpeiseRepository repository, IWebHostEnvironment env)
{
_repository = repository;
2022-05-30 09:22:35 +02:00
_path = System.IO.Path.Combine(env.ContentRootPath, "data", "images", "speisen");
}
[HttpGet]
2022-05-20 11:10:58 +02:00
// Muss etwas zurück geben
public IEnumerable<Speise> Get()
{
2022-05-30 09:22:35 +02:00
return _repository.GetSpeisen();
2022-05-20 11:10:58 +02:00
}
// api/speisen/1 wird zur angegebenen id geroutet
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var speise = _repository.GetSpeiseById(id);
if (speise == null)
2022-05-20 11:10:58 +02:00
{
return NotFound(); // StatusCode 404
}
return Ok(speise);
}
// Zum Hinzufügen von Daten
[HttpPost]
public IActionResult Post([FromBody] Speise speise)
{
2022-05-30 09:22:35 +02:00
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // Alle Felder müssen ausgefüllt werden, stonst Statuscode 400
}
var result = _repository.CreateSpeise(speise);
2022-05-30 09:22:35 +02:00
return CreatedAtAction("Get", new { id = result.Id }, result); //Name der Action (Get), gibt Statuscode 201 zurück
}
[HttpPut("{id}")]
2022-05-30 09:22:35 +02:00
// Zum ändern der Daten der Speise
public IActionResult Put(int id, [FromBody] Speise speise)
{
if (id != speise.Id)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
2022-05-30 09:22:35 +02:00
if (_repository.GetSpeiseById(id) == null)
{
return NotFound();
}
2022-05-30 09:22:35 +02:00
var result = _repository.UpdateSpeise(speise);
return Ok(result);
2022-05-27 10:24:35 +02:00
}
2022-05-27 10:24:35 +02:00
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
2022-05-30 09:22:35 +02:00
if (_repository.GetSpeiseById(id) == null)
2022-05-27 10:24:35 +02:00
{
return NotFound();
}
_repository.DeleteSpeise(id);
return NoContent();
}
2022-05-30 09:22:35 +02:00
// Über die Id wird das Image ausgegeben
[HttpGet("{id}/image")]
public IActionResult Image(int id)
{
var file = System.IO.Path.Combine(_path, $"{id}.jpg");
if (System.IO.File.Exists(file))
{
var bytes = System.IO.File.ReadAllBytes(file);
return File(bytes, "image/jpeg");
}
return NotFound();
}
}
}