API
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

UserController.cs 2.0KB

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. [Authorize]
  11. [Route("api/[controller]")]
  12. [ApiController]
  13. public class UserController : ControllerBase
  14. {
  15. private readonly IRepository<User> _Repo;
  16. public UserController(IRepository<User> repo)
  17. {
  18. _Repo = repo;
  19. }
  20. [Authorize(Roles = Role.SuperAdmin)]
  21. [HttpGet]
  22. public IActionResult Get()
  23. {
  24. return new OkObjectResult(_Repo.GetAll());
  25. }
  26. [HttpGet("{id}")]
  27. public IActionResult Get(int id)
  28. {
  29. var currentUserId = int.Parse(User.Identity.Name);
  30. if (id != currentUserId && !User.IsInRole(Role.SuperAdmin))
  31. {
  32. return Forbid();
  33. }
  34. return new OkObjectResult(_Repo.Get(x => x.Id == id));
  35. }
  36. [HttpPost()]
  37. public IActionResult Post([FromBody] User user)
  38. {
  39. using (var scope = new TransactionScope())
  40. {
  41. _Repo.Insert(user);
  42. scope.Complete();
  43. return CreatedAtAction(nameof(Get), new { id = user.Id }, user);
  44. }
  45. }
  46. [HttpPut()]
  47. public IActionResult Put([FromBody] User user)
  48. {
  49. if (user != null)
  50. {
  51. using (var scope = new TransactionScope())
  52. {
  53. _Repo.Update(user);
  54. scope.Complete();
  55. return new OkResult();
  56. }
  57. }
  58. return new NoContentResult();
  59. }
  60. [HttpDelete("{id}")]
  61. public IActionResult Delete(int id)
  62. {
  63. _Repo.RemoveAtId(id);
  64. return new OkResult();
  65. }
  66. }
  67. }