104 lines
2.6 KiB
C#
104 lines
2.6 KiB
C#
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Logging;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using TodoApp.API.Data;
|
|
using TodoApp.API.Models;
|
|
|
|
namespace TodoApp.Controllers
|
|
{
|
|
[ApiController]
|
|
[Route("api/[controller]")]
|
|
[Authorize]
|
|
public class TodoController : ControllerBase
|
|
{
|
|
private readonly TodoAppContext _context;
|
|
|
|
public TodoController(TodoAppContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
[HttpGet]
|
|
public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
|
|
{
|
|
return await _context.TodoItems.ToListAsync();
|
|
}
|
|
|
|
[HttpGet("{id}")]
|
|
public async Task<ActionResult<TodoItem>> GetTodoItem(long id)
|
|
{
|
|
var todoItem = await _context.TodoItems.FindAsync(id);
|
|
|
|
if (todoItem == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
|
|
return todoItem;
|
|
}
|
|
|
|
[HttpPut("{id}")]
|
|
public async Task<IActionResult> PutTodoItem(long id, TodoItem todoItem)
|
|
{
|
|
if (id != todoItem.ID)
|
|
{
|
|
return BadRequest();
|
|
}
|
|
|
|
_context.Entry(todoItem).State = EntityState.Modified;
|
|
|
|
try
|
|
{
|
|
await _context.SaveChangesAsync();
|
|
}
|
|
catch (DbUpdateConcurrencyException)
|
|
{
|
|
if (!TodoItemExists(id))
|
|
{
|
|
return NotFound();
|
|
}
|
|
else
|
|
{
|
|
throw;
|
|
}
|
|
}
|
|
|
|
return NoContent();
|
|
}
|
|
|
|
[HttpPost]
|
|
public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem todoItem)
|
|
{
|
|
_context.TodoItems.Add(todoItem);
|
|
await _context.SaveChangesAsync();
|
|
|
|
return CreatedAtAction("PostTodoItem", new { id = todoItem.ID }, todoItem);
|
|
}
|
|
|
|
[HttpDelete("{id}")]
|
|
public async Task<IActionResult> DeleteTodoItem(long id)
|
|
{
|
|
var todoItem = await _context.TodoItems.FindAsync(id);
|
|
if (todoItem == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
|
|
_context.TodoItems.Remove(todoItem);
|
|
await _context.SaveChangesAsync();
|
|
|
|
return NoContent();
|
|
}
|
|
|
|
private bool TodoItemExists(long id)
|
|
{
|
|
return _context.TodoItems.Any(e => e.ID == id);
|
|
}
|
|
}
|
|
}
|