您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

UserController.cs 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Microsoft.AspNetCore.Mvc;
  2. using ProRestaurant.Models.Accounts;
  3. using ProRestaurant.Repository.Accounts;
  4. using System.Transactions;
  5. namespace ProRestaurant.Controllers.Accounts
  6. {
  7. [Route("api/[controller]")]
  8. [ApiController]
  9. public class UserController : ControllerBase
  10. {
  11. private readonly IUserRepository userRepository;
  12. public UserController(IUserRepository userRepo)
  13. {
  14. userRepository = userRepo;
  15. }
  16. [HttpGet]
  17. public IActionResult Get()
  18. {
  19. return new OkObjectResult(userRepository.GetUsers());
  20. }
  21. [HttpGet("{id}")]
  22. public IActionResult Get(int id)
  23. {
  24. var user = userRepository.GetUser(u => u.Id == id);
  25. return new OkObjectResult(user);
  26. }
  27. [HttpGet("Login/{username}/{password}")]
  28. public IActionResult Login(string username, string password)
  29. {
  30. return new OkObjectResult(userRepository.Login(username, password));
  31. }
  32. [HttpPost]
  33. public IActionResult Post([FromBody] User user)
  34. {
  35. using (var scope = new TransactionScope())
  36. {
  37. userRepository.Insert(user);
  38. scope.Complete();
  39. return CreatedAtAction(nameof(Get), new { id = user.Id }, user);
  40. }
  41. }
  42. [HttpPut]
  43. public IActionResult Put([FromBody] User user)
  44. {
  45. if (user != null)
  46. {
  47. using (var scope = new TransactionScope())
  48. {
  49. userRepository.Update(user);
  50. scope.Complete();
  51. return new OkResult();
  52. }
  53. }
  54. return new NoContentResult();
  55. }
  56. [HttpDelete("{id}")]
  57. public IActionResult Delete(int id)
  58. {
  59. userRepository.Remove(userRepository.GetUser(u => u.Id == id));
  60. return new OkResult();
  61. }
  62. }
  63. }