DocumentController.cs 6.8 KB

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