[英]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.