■ IConfiguration 인터페이스를 사용해 appsettings.json 파일 설정 값을 구하는 방법을 보여준다.
▶ appsettings.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
{ "Position" : { "Title" : "Editor", "Name" : "Smith" }, "TestKey" : "Test Value", "Logging" : { "LogLevel" : { "Default" : "Information", "Microsoft" : "Warning", "Microsoft.Hosting.Lifetime" : "Information" } }, "AllowedHosts" : "*" } |
▶ Controllers/TestController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using System.Text; namespace TestProject.Controllers { /// <summary> /// 테스트 컨트롤러 /// </summary> public class TestController : Controller { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 구성 /// </summary> private IConfiguration configuration; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - TestController(configuration) /// <summary> /// 생성자 /// </summary> /// <param name="configuration">구성</param> public TestController(IConfiguration configuration) { this.configuration = configuration; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 인덱스 페이지 처리하기 - Index() /// <summary> /// 인덱스 페이지 처리하기 /// </summary> /// <returns>액션 결과</returns> public IActionResult Index() { string testValue = this.configuration["TestKey" ]; string title = this.configuration["Position:Title" ]; string name = this.configuration["Position:Name" ]; string defaultLogLevel = this.configuration["Logging:LogLevel:Default"]; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"Test Key : {testValue}" ); stringBuilder.AppendLine($"Title : {title}" ); stringBuilder.AppendLine($"Name : {name}" ); stringBuilder.AppendLine($"Default Log Level : {defaultLogLevel}"); return Content(stringBuilder.ToString()); } #endregion } } |