68 lines
1.9 KiB
C#
68 lines
1.9 KiB
C#
// все про роли (админ клиент и тд)
|
||
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();
|
||
}
|
||
}
|