Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

C# - appsettings.json 파일의 설정값이 적용 안 된다면?

이상하군요, 분명히 웹 애플리케이션의 배포 경로에는 appsettings.json 파일이 있고, 그 안에 설정값까지 넣어두었습니다.

$ cat appsettings.json
{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },

    "AllowedHosts": "*",

    "ConnectionStrings": {
        "DBLocal": "...[생략]..."
    }
}

그런데 Microsoft.Extensions.Configuration.IConfiguration.GetConnectionString 메서드에서는 null을 반환합니다. 반면, 비주얼 스튜디오에서 디버깅을 해보면 ^^; 값이 잘 반환됩니다.

검색해 보니까,

Published .Net Core 2 application does not read appsettings.json file
; https://stackoverflow.com/questions/50578013/published-net-core-2-application-does-not-read-appsettings-json-file

Current Directory를 기준으로 찾기 때문이라고 합니다. 그러니까, 아래와 같은 식으로 실행하면 안 되는 것입니다.

// 아래와 같은 경우라면, "/appsettings.json" 경로의 파일을 찾게 되므로 의도한 대로 실행이 안 됨.

$ pwd
/

$ dotnet /app/core3web/Core3Web.dll

대신 이렇게 실행해야 합니다.

// 아래의 경우라면, "/app/core3web/appsettings.json" 경로의 파일을 찾게 되므로 의도한 대로 실행.

$ cd /app/core3web
$ dotnet Core3Web.dll

쉬운 내용이다 보니 너무 쉽게 간과할 수 있던 부분입니다. ^^ 따라서 만약 다른 경로에서 "dotnet /app/core3web/Core3Web.dll"과 같은 식으로 실행하는 것도 허용하고 싶다면 Current Directory를 변경해야 합니다. "Published .Net Core 2 application does not read appsettings.json file" 글의 답변에는 이에 대한 해결책으로 AppContext.BaseDirectory를 이용했다고 하는데 좋은 우회책인 것 같습니다. ^^

namespace Core3Web;

public class Program
{
    public static void Main(string[] args)
    {
        Environment.CurrentDirectory = AppContext.BaseDirectory;
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup();
                webBuilder.ConfigureKestrel(serverOptions =>
                {
                    serverOptions.ListenAnyIP(6001);
                });
            });
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 8/20/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [136]  137  138  139  140  141  142  143  144  145  146  147  148  149  150  ...
NoWriterDateCnt.TitleFile(s)
1738정성태8/23/201425623.NET Framework: 456. C# - CAS를 이용한 Lock 래퍼 클래스파일 다운로드1
1737정성태8/20/201422228VS.NET IDE: 93. Visual Studio 2013 동기화 문제
1736정성태8/19/201428849VC++: 79. [부연] CAS Lock 알고리즘은 과연 빠른가? [2]파일 다운로드1
1735정성태8/19/201421658.NET Framework: 455. 닷넷 사용자 정의 예외 클래스의 최소 구현 코드 - 두 번째 이야기
1734정성태8/13/201423055오류 유형: 237. Windows Media Player cannot access the file. The file might be in use, you might not have access to the computer where the file is stored, or your proxy settings might not be correct.
1733정성태8/13/201429208.NET Framework: 454. EmptyWorkingSet Win32 API를 사용하는 C# 예제파일 다운로드1
1732정성태8/13/201437833Windows: 99. INetCache 폴더가 다르게 보이는 이유
1731정성태8/11/201430169개발 환경 구성: 235. 점(.)으로 시작하는 파일명을 탐색기에서 만드는 방법
1730정성태8/11/201425347개발 환경 구성: 234. Royal TS의 터미널(Terminal) 연결에서 한글이 깨지는 현상 해결 방법
1729정성태8/11/201421253오류 유형: 236. SqlConnection - The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.
1728정성태8/8/201433836.NET Framework: 453. C# - 오피스 파워포인트(Powerpoint) 파일을 WinForm에서 보는 방법파일 다운로드1
1727정성태8/6/201424067오류 유형: 235. SignalR 오류 메시지 - Counter 'Messages Bus Messages Published Total' does not exist in the specified Category. [2]
1726정성태8/6/201422462오류 유형: 234. IIS Express에서 COM+ 사용 시 SecurityException - "Requested registry access is not allowed" 발생
1725정성태8/6/201424523오류 유형: 233. Visual Studio 2013 Update3 적용 후 Microsoft.VisualStudio.Web.PageInspector.Runtime 모듈에 대한 FileNotFoundException 예외 발생
1724정성태8/5/201429340.NET Framework: 452. .NET System.Threading.Thread 개체에서 Native Thread Id를 구하는 방법 - 두 번째 이야기 [1]파일 다운로드1
1723정성태7/29/201462007개발 환경 구성: 233. DirectX 9 예제 프로젝트 빌드하는 방법 [3]파일 다운로드1
1722정성태7/25/201423897오류 유형: 232. IIS 500 Internal Server Error - NTFS 암호화된 폴더에 웹 애플리케이션이 위치한 경우
1721정성태7/24/201427654.NET Framework: 451. 함수형 프로그래밍 개념 - 리스트 해석(List Comprehension)과 순수 함수 [2]
1720정성태7/23/201425090개발 환경 구성: 232. C:\WINDOWS\system32\LogFiles\HTTPERR 폴더에 로그 파일을 남기지 않는 설정
1719정성태7/22/201429287Math: 13. 동전을 여러 더미로 나누는 경우의 수 세기(Partition Number) - 두 번째 이야기파일 다운로드1
1718정성태7/19/201438888Math: 12. HTML에서 수학 관련 기호/수식을 표현하기 위한 방법 - MathJax.js [4]
1716정성태7/17/201438926개발 환경 구성: 231. PC 용 무료 안드로이드 에뮬레이터 - genymotion
1715정성태7/13/201432987기타: 47. 운영체제 종료 후에도 USB 외장 하드의 전원이 꺼지지 않는 경우 [3]
1714정성태7/11/201422589VS.NET IDE: 92. Visual Studio 2013을 지원하는 IL Support 확장 도구
1713정성태7/11/201446515Windows: 98. 윈도우 시스템 디스크 용량 확보를 위한 "Package Cache" 폴더 이동 [1]
1712정성태7/10/201435399.NET Framework: 450. 영문 윈도우에서 C# 콘솔 프로그램의 유니코드 출력 방법 [3]
... [136]  137  138  139  140  141  142  143  144  145  146  147  148  149  150  ...