[英]User Secrets not being read - FileProvider is showing project's debug path
我有一個奇怪的問題,在我的解決方案中的一個測試項目中,關聯的用戶機密運行良好,但在另一個新項目中,它們根本沒有被讀取,並且在查看 ConfigurationBuilder 時,FileProvider.Root 被設置為調試文件夾。
為了測試,我在調試文件夾中放置了一個 secrets.json 文件,它確實被讀取了。
讀取配置的代碼在解決方案之間非常相似,如下所示:
public IConfigurationRoot GetConfig()
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddUserSecrets<ConfigClass1>()
.AddUserSecrets<ConfigClass2>()
...
.Build();
return configuration;
}
編輯:該項目確實包含 UserSecretsId:
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UserSecretsId>bfe3...</UserSecretsId>
<OutputType>Library</OutputType>
</PropertyGroup>
我在嘗試在 a.net 6 docker 容器中添加 UserSecrets 時也遇到了這個問題。
你(和我)得到的路徑源於:
UserSecrets 在后台使用的 JsonConfigurationSource 允許將null
作為文件提供程序傳遞,並且 JsonConfigurationSource 將嘗試通過默認為AppContext.BaseDirectory?? string.Empty
AppContext.BaseDirectory?? string.Empty
.空。
將其包裝起來,由於這部分,提供者最初是 null:
最終試圖確定結果是否
https://source.dot.net/#Microsoft.Extensions.Configuration.UserSecrets/PathHelper.cs,26
public static string GetSecretsPathFromSecretsId(string userSecretsId)
{
if (string.IsNullOrEmpty(userSecretsId))
{
throw new ArgumentException(SR.Common_StringNullOrEmpty, nameof(userSecretsId));
}
int badCharIndex = userSecretsId.IndexOfAny(Path.GetInvalidFileNameChars());
if (badCharIndex != -1)
{
throw new InvalidOperationException(
string.Format(
SR.Error_Invalid_Character_In_UserSecrets_Id,
userSecretsId[badCharIndex],
badCharIndex));
}
const string userSecretsFallbackDir = "DOTNET_USER_SECRETS_FALLBACK_DIR";
// For backwards compat, this checks env vars first before using Env.GetFolderPath
string? appData = Environment.GetEnvironmentVariable("APPDATA");
string? root = appData // On Windows it goes to %APPDATA%\Microsoft\UserSecrets\
?? Environment.GetEnvironmentVariable("HOME") // On Mac/Linux it goes to ~/.microsoft/usersecrets/
?? Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
?? Environment.GetEnvironmentVariable(userSecretsFallbackDir); // this fallback is an escape hatch if everything else fails
if (string.IsNullOrEmpty(root))
{
throw new InvalidOperationException(SR.Format(SR.Error_Missing_UserSecretsLocation, userSecretsFallbackDir));
}
return !string.IsNullOrEmpty(appData)
? Path.Combine(root, "Microsoft", "UserSecrets", userSecretsId, SecretsFileName)
: Path.Combine(root, ".microsoft", "usersecrets", userSecretsId, SecretsFileName);
}
已驗證。
如您所見,GetSecretsPathFromSecretsId 嘗試了很多選項以確定包含您的機密的 secrets.json 的位置。 在我的例子中,它默認為 /home 目錄,因為 linux 上沒有應用數據。我沒想到會這樣,因為我沒有將我的用戶機密裝載到那個非默認目錄中,所以根本就沒有目錄,所以我列出的檢查確定我的文件提供者是 null 並默認為 AppContext.BaseDirectory。
希望這有助於理解問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.