API
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

UserController.cs 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Transactions;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Mvc;
  4. using UnivateProperties_API.Containers.Users;
  5. using UnivateProperties_API.Model.Users;
  6. using UnivateProperties_API.Repository;
  7. using UnivateProperties_API.Repository.Users;
  8. namespace User_API.Controllers
  9. {
  10. [Route("api/[controller]")]
  11. [ApiController]
  12. public class UserController : ControllerBase
  13. {
  14. private readonly IUserRepository _Repo;
  15. public UserController(IUserRepository repo)
  16. {
  17. _Repo = repo;
  18. }
  19. [HttpGet]
  20. public IActionResult Get()
  21. {
  22. return new OkObjectResult(_Repo.GetAll());
  23. }
  24. [HttpGet("{id}")]
  25. public IActionResult Get(int id)
  26. {
  27. var currentUserId = int.Parse(User.Identity.Name);
  28. if (id != currentUserId && !User.IsInRole(Role.SuperAdmin))
  29. {
  30. return Forbid();
  31. }
  32. return new OkObjectResult(_Repo.Get(x => x.Id == id));
  33. }
  34. [HttpPost()]
  35. public IActionResult Post([FromBody] User user)
  36. {
  37. using (var scope = new TransactionScope())
  38. {
  39. _Repo.Insert(user);
  40. scope.Complete();
  41. return CreatedAtAction(nameof(Get), new { id = user.Id }, user);
  42. }
  43. }
  44. [HttpPut()]
  45. public IActionResult Put([FromBody] UserDto user)
  46. {
  47. if (user != null)
  48. {
  49. using (var scope = new TransactionScope())
  50. {
  51. _Repo.Update(user);
  52. scope.Complete();
  53. return new OkResult();
  54. }
  55. }
  56. return new NoContentResult();
  57. }
  58. [HttpDelete("{id}")]
  59. public IActionResult Delete(int id)
  60. {
  61. _Repo.RemoveAtId(id);
  62. return new OkResult();
  63. }
  64. }
  65. }