---
# System prepended metadata

title: 'User Secret : 避免將ConnectionString上傳到github中'
tags: [MVC應用]

---

# 簡單避免將連接字串上傳到github中 - User Secret
## 1. Connection String在哪 -> appsettings.json
預設資料庫連接字串包含在專案的 appsettings.json 檔案中
可能會像以下這樣
注意不可以把你要隱藏的連接字串打上去 必須空字串
```csharp=
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "" //必須像這樣空字串
  },
  "AzureStorageConfig": {
    "ConnectionString": "", //必須像這樣空字串
    "ContainerName": "thumbnailsphoto"
  },
  "AllowedHosts": "*"
}

```
## 2. 如何設定秘密 -> Secret Manager
### 2.1 使用CLI初始化
`dotnet user-secrets init`
![image](https://hackmd.io/_uploads/BJ49kXK9R.png)
This command will add a **UserSecretsId** to your project file (.csproj).

### 2.2 設定連接字串
`dotnet user-secrets set "AzureStorageConfig:ConnectionString" "YOUR_ACTUAL_CONNECTION_STRING"`
或是
`dotnet user-secrets set "ConnectionStrings:DefaultConnection" "YOUR_ACTUAL_CONNECTION_STRING"`
把YOUR_ACTUAL_CONNECTION_STRING替換成你自己的連接字串
### 2.3 在哪裡查看設定好的連接字串
可以對專案按右鍵管理使用者秘密看到
![image](https://hackmd.io/_uploads/ryO3zQKqA.png)

或是使用CLI
`dotnet user-secrets list`

## 3. 將user secrets加入Configuration中
Program.cs中加入設定 就可以正常連線使用了
```csharp=
var builder = WebApplication.CreateBuilder(args);

// Add this line to include user secrets in Development environment
if (builder.Environment.IsDevelopment())
{
    builder.Configuration.AddUserSecrets<Program>(); //加入這行
    
}

```


<br></br>
參考資料：
https://learn.microsoft.com/zh-tw/aspnet/core/security/app-secrets?view=aspnetcore-8.0&tabs=windows