UserController.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Configuration;
  5. using Newtonsoft.Json.Linq;
  6. namespace jsonapi.Controllers
  7. {
  8. [ApiController]
  9. [Route("user")]
  10. [Produces("application/json")]
  11. public class UserController : ControllerBase
  12. {
  13. private IConfiguration configuration;
  14. private Library.JsonFileReader jsonFileReader;
  15. public UserController(IConfiguration config)
  16. {
  17. configuration = config;
  18. jsonFileReader = Library.JsonFileReader.GetInstance();
  19. }
  20. [HttpGet("{id}")]
  21. public IActionResult Get(string id)
  22. {
  23. string worldPath = configuration.GetSection("jsonapi").GetValue<string>("world");
  24. var fileName = worldPath + "/users.json";
  25. try
  26. {
  27. var json = jsonFileReader.Read(fileName);
  28. string userFilePath = worldPath + "/users/" + json[id] + ".json";
  29. try
  30. {
  31. var userJson = jsonFileReader.Read(userFilePath);
  32. dynamic simpleUser = new
  33. {
  34. name = userJson["name"],
  35. };
  36. return Ok(simpleUser);
  37. }
  38. catch (Exception)
  39. {
  40. dynamic errorObject = new
  41. {
  42. errorCode = StatusCodes.Status404NotFound,
  43. errorMessage = "404 Error: Invalid user data."
  44. };
  45. return StatusCode(errorObject.errorCode, errorObject);
  46. }
  47. }
  48. catch (Exception)
  49. {
  50. dynamic errorObject = new
  51. {
  52. errorCode = StatusCodes.Status500InternalServerError,
  53. errorMessage = "500 Error: Something went wrong. Please contact the administrator for assistance."
  54. };
  55. return StatusCode(errorObject.errorCode, errorObject);
  56. }
  57. }
  58. }
  59. }