티스토리 뷰
반응형
ASP.NET Core에서는 appsettings.json에 넣기 어려운 민감한 정보(예: DB 비밀번호, API Key)를 User Secrets 기능으로 관리할 수 있습니다. 이 기능은 개발 환경에서만 사용되고, 실제 배포 시에는 Azure Key Vault나 운영체제의 Environment Variables 같은 다른 방법을 쓰는 게 일반적입니다.
User Secrets 추가 방법
- 프로젝트에 User Secrets 추가
[명령 프롬프트]에서 프로젝트 루트로 이동한 후 다음 명령 실행:
이 명령을 실행하면 .csproj 파일에 UserSecretsId 속성이 추가되게 됩니다. (아래 예시)dotnet user-secrets init
만약 이미 User Secrets가 프로젝트에 추가된 상태라면 아래와 같은 메시지가 나타납니다.<PropertyGroup> <UserSecretsId>aspnet-core.web-00000000-0000-0000-0000-000000000000</UserSecretsId> </PropertyGroup>The MSBuild project 'C:\aspnet-core.web.csproj' has already been initialized with a UserSecretsId. - 시크릿 값 추가하기
[명령 프롬프트]에서 아래와 같은 형태로 명령을 입력하세요.
부모/자식을 구분하는 구분자는 ":"으로 구분하시면 됩니다. 예로 들면 아래와 같습니다.dotnet user-secrets set "KEY" "VALUE"#DB 연결문자열 dotnet user-secrets set "ConnectionStrings:DefaultConnection" "Server=.;Database=dbname;User Id=sa;Password=pw1234;" #ApiKeys 아래 TestServcie 값 설정 dotnet user-secrets set "ApiKeys:TestService" "abcd234" - C# 코드에서 불러오기
C#코드에서는 기존과 동일하게 Configuration을 통해서 값을 불러올 수 있습니다. 마찬가지로 부모/자식을 구분하는 구분자는 ":"으로 구분합니다.//예: Dependency Injection을 사용하는 경우 public interface IAppSettings { string? DefaultConnection { get; } string? TestServiceKey { get; } } public class AppSettings : IAppSettings { public string? DefaultConnection { get { return _configuration.GetConnectionString("DefaultConnection"); } } public string? TestServiceKey { get { return _configuration.GetValue<string>("ApiKeys:TestService"); } } private IConfiguration _configuration; public AppSettings(IConfiguration configuration) { _configuration = configuration; } } //예: Program.cs 또는 Startup.cs에서 값을 읽는 경우 var builder = WebApplication.CreateBuilder(args); string? connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); string? testServiceKey = builder.Configuration["ApiKeys:TestService"];
User Secrets 조회 및 삭제
현재 추가된 시크릿 내역을 확인하려면 [명령 프롬프트]에서 아래 명령을 실행하세요.
dotnet user-secrets list
현재 추가된 시크릿 항목을 삭제하려면 아래 명령을 실행하세요.
dotnet user-secrets remove "ApiKeys:TestService"
'Web > ASP.NET Core' 카테고리의 다른 글
| AddIdentity, AddApiEndpoints, AddIdentityApiEndpoints (0) | 2026.09.22 |
|---|---|
| [ASP.NET] IIS 호스팅 시 CS0433 오류 (0) | 2025.06.27 |
| ASP.NET Core에 Vue앱 추가하기 (0) | 2023.11.15 |
| [ASP.NET Core] 배포 프로필 (.pubxml) (1) | 2022.04.01 |
| Application State vs 전역 Static 변수 (0) | 2019.08.19 |
| ASP.NET Core Identity 에러 지역화 (0) | 2019.04.08 |
댓글
최근에 올라온 글
최근에 달린 댓글
TAG
- Xamarin.Forms 요약
- windows
- VisualStudio
- TypeScript
- React
- WPF
- Vue
- linux
- material-ui
- MS SQL
- .NET Standard
- Xamarin.Forms eBook
- Android
- Xamarin.iOS
- Xamarin.Forms
- npm
- ios
- Xamarin
- flutter
- ASP.NET Core
- Total
- Today
- Yesterday