DocumentController.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. using System.Diagnostics;
  2. using bitforum.Models;
  3. using bitforum.Models.Page;
  4. using Microsoft.AspNetCore.Authorization;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.EntityFrameworkCore;
  7. namespace bitforum.Controllers.Page
  8. {
  9. [Authorize]
  10. [Route("Page")]
  11. public class DocumentController : Controller
  12. {
  13. private readonly ILogger<DocumentController> _logger;
  14. private readonly DefaultDbContext _db;
  15. private readonly IConfiguration _config;
  16. private readonly string _IndexViewPath = "~/Views/Page/Document/Index.cshtml";
  17. private readonly string _WriteViewPath = "~/Views/Page/Document/Write.cshtml";
  18. private readonly string _EditViewPath = "~/Views/Page/Document/Edit.cshtml";
  19. public DocumentController(ILogger<DocumentController> logger, DefaultDbContext db, IConfiguration config)
  20. {
  21. _logger = logger;
  22. _db = db;
  23. _config = config;
  24. }
  25. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  26. public IActionResult Error()
  27. {
  28. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  29. }
  30. [HttpGet("Document")]
  31. public IActionResult Index()
  32. {
  33. ViewBag.siteURL = _config["AppConfig:AppName"];
  34. ViewBag.Documents = _db.Document.OrderByDescending(c => c.ID).ToList();
  35. return View(_IndexViewPath);
  36. }
  37. [HttpGet("Document/Write")]
  38. public IActionResult Write()
  39. {
  40. ViewBag.siteURL = _config["AppConfig:AppName"];
  41. return View(_WriteViewPath);
  42. }
  43. [HttpPost("Document/Create")]
  44. public async Task<IActionResult> Create(Document request)
  45. {
  46. try
  47. {
  48. if (!ModelState.IsValid)
  49. {
  50. throw new Exception("유효성 검사에 실패하였습니다.");
  51. }
  52. // 중복확인
  53. if (await _db.Document.AnyAsync(c => c.Code == request.Code))
  54. {
  55. throw new Exception("이미 존재하는 Code 주소입니다.");
  56. }
  57. request.UpdatedAt = null;
  58. request.CreatedAt = DateTime.Now;
  59. _db.Document.Add(request);
  60. int affectedRows = await _db.SaveChangesAsync();
  61. if (affectedRows <= 0)
  62. {
  63. throw new Exception("문서 등록 중 오류가 발생했습니다.");
  64. }
  65. string message = "문서가 정상적으로 등록되었습니다.";
  66. TempData["SuccessMessage"] = message;
  67. _logger.LogInformation(message);
  68. return RedirectToAction("Index");
  69. }
  70. catch (Exception e)
  71. {
  72. _logger.LogError(e, e.Message);
  73. TempData["ErrorMessages"] = e.Message;
  74. return View(_WriteViewPath, request);
  75. }
  76. }
  77. [HttpGet("Document/Edit/{id}")]
  78. public async Task<IActionResult> Edit(int id)
  79. {
  80. ViewBag.siteURL = _config["AppConfig:AppName"];
  81. try
  82. {
  83. if (id <= 0)
  84. {
  85. throw new Exception("유효하지 않은 문서 ID입니다.");
  86. }
  87. var document = await _db.Document.FirstAsync(c => c.ID == id);
  88. if (document is null)
  89. {
  90. throw new Exception("사용자 정보를 찾을 수 없습니다.");
  91. }
  92. return View(_EditViewPath, document);
  93. }
  94. catch (Exception e)
  95. {
  96. _logger.LogError(e, e.Message);
  97. TempData["ErrorMessages"] = e.Message;
  98. return Index();
  99. }
  100. }
  101. [HttpPost("Document/Update")]
  102. public async Task<IActionResult> Update(Document request)
  103. {
  104. try
  105. {
  106. if (!ModelState.IsValid)
  107. {
  108. throw new Exception("유효성 검사에 실패하였습니다.");
  109. }
  110. // 중복확인
  111. if (await _db.Document.AnyAsync(c => c.Code == request.Code && c.ID != request.ID))
  112. {
  113. throw new Exception("이미 존재하는 Code 주소입니다.");
  114. }
  115. // 기존 문서 조회
  116. var document = await _db.Document.FindAsync(request.ID);
  117. if (document is null)
  118. {
  119. throw new Exception("사용자 정보를 찾을 수 없습니다.");
  120. }
  121. document.IsActive = request.IsActive;
  122. document.Code = request.Code;
  123. document.Subject = request.Subject;
  124. document.Content = request.Content;
  125. document.UpdatedAt = DateTime.Now;
  126. _db.Document.Update(document);
  127. int affectedRows = await _db.SaveChangesAsync();
  128. if (affectedRows <= 0)
  129. {
  130. throw new Exception("문서 수정 중 오류가 발생했습니다.");
  131. }
  132. string message = "문서가 정상적으로 수정되었습니다.";
  133. TempData["SuccessMessage"] = message;
  134. _logger.LogInformation(message);
  135. return RedirectToAction("Edit", new { request.ID });
  136. }
  137. catch (Exception e)
  138. {
  139. _logger.LogError(e, e.Message);
  140. TempData["ErrorMessages"] = e.Message;
  141. return View(_EditViewPath, request);
  142. }
  143. }
  144. [HttpGet("Document/Delete/{id}")]
  145. public async Task<IActionResult> Delete(int id)
  146. {
  147. try
  148. {
  149. if (id <= 0)
  150. {
  151. throw new Exception("유효하지 않은 문서 ID입니다.");
  152. }
  153. var document = await _db.Document.FindAsync(id);
  154. if (document == null)
  155. {
  156. throw new Exception("문서 정보를 찾을 수 없습니다.");
  157. }
  158. _db.Document.Remove(document);
  159. int affectedRows = await _db.SaveChangesAsync();
  160. if (affectedRows <= 0)
  161. {
  162. throw new Exception("문서 삭제 중 오류가 발생했습니다.");
  163. }
  164. string message = "문서가 정상적으로 삭제되었습니다.";
  165. TempData["SuccessMessage"] = message;
  166. _logger.LogInformation(message);
  167. return RedirectToAction("Index");
  168. }
  169. catch (Exception e)
  170. {
  171. _logger.LogError(e, e.Message);
  172. TempData["ErrorMessages"] = e.Message;
  173. return Index();
  174. }
  175. }
  176. }
  177. }