DemO/DEMO/Controllers/RolesController.cs

68 lines
1.9 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// все про роли (админ клиент и тд)
using DEMO.Data; // база
using DEMO.Models; // роли
using Microsoft.AspNetCore.Mvc; // контроллер
using Microsoft.EntityFrameworkCore; // база
namespace DEMO.Controllers;
[ApiController] // это api
[Route("api/[controller]")] // адрес будет api/roles
public class RolesController : ControllerBase
{
private readonly AppDbContext _context; // база
// запоминаю базу
public RolesController(AppDbContext context)
{
_context = context;
}
// отдать все роли
[HttpGet]
public async Task<IActionResult> GetRoles()
{
var roles = await _context.Roles.ToListAsync(); // беру все
return Ok(roles);
}
// добавить роль
[HttpPost]
public async Task<IActionResult> CreateRole(Role role) // приходит название
{
_context.Roles.Add(role); // добавляю
await _context.SaveChangesAsync(); // сохраняю
return Ok(role);
}
// изменить роль
[HttpPut("{id}")]
public async Task<IActionResult> UpdateRole(int id, Role role)
{
var existingRole = await _context.Roles.FindAsync(id); // ищу старую
if (existingRole == null)
return NotFound();
existingRole.Name = role.Name; // меняю название
await _context.SaveChangesAsync(); // сохраняю
return Ok(existingRole);
}
// удалить роль
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteRole(int id)
{
var role = await _context.Roles.FindAsync(id); // ищу
if (role == null)
return NotFound();
_context.Roles.Remove(role); // удаляю
await _context.SaveChangesAsync(); // сохраняю
return NoContent();
}
}