[英]Unable to get value from appsettings.json
在新創建的asp.net core 2.0 Web API項目中,我想使用來自appsettings.json的值:
{
"JWTSettings":
{
"SecretKey": "blahblahbla",
"Issuer": "QuinCApi",
"Audience": "http://localhost:10080/",
"LifeTimeInMinutes": 1
}
}
並為此創建了模型
public class JWTSettings
{
public string SecretKey { get; set; }
public string Issuer { get; set; }
public string Audience { get; set; }
public int LifeTimeInMinutes { get; set; }
}
在Startup.cs中,我使用以下方法注冊了它:
在構造函數中:
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
在ConfigureServices方法中:
var appSettings = Configuration.GetSection("JWTSettings");
services.Configure<JWTSettings>(appSettings);
然后,我嘗試使用DI來獲取值,但是有時它為某些字段返回正常值,有時(實際上總是)返回“ ValuesAPI”,而不是實際值。 我究竟做錯了什么?
PS Configuration.GetValue <>()執行相同的技巧。
在使用DI訪問模型類JWTSettings
的屬性的方法中,應使用.NET Core中的IOptions<T>
模式遵循以下方法。
public SampleDIMethod(IOptions<JWTSettings> settings)
{
//returns an object of type JWTSettings
var securitySettings = settings.Value;
}
請參考下面的鏈接
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.