【问题标题】:Unable to get value from appsettings.json无法从 appsettings.json 获取价值
【发布时间】:2017-08-22 12:37:59
【问题描述】:

在新创建的 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”,但不是真正的值。我做错了什么?

附: Configuration.GetValue() 做同样的事情。

【问题讨论】:

  • 您可以将代码发布到您使用 DI 访问模型类中的值的位置吗?还有你的意思是“它有时会返回某些字段的正常值,有时(实际上总是)返回“ValuesAPI”,
  • 您能否添加使用 DI 获得的值?

标签: c# asp.net json asp.net-web-api asp.net-core


【解决方案1】:

在您使用 DI 访问模型类属性的方法中 JWTSettings 你应该按照下面的方法在 .NET Core 中使用 IOptions&lt;T&gt; 模式。

public SampleDIMethod(IOptions<JWTSettings> settings)
{
 //returns an object of type JWTSettings
  var securitySettings = settings.Value; 
 }

请参考以下链接

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration

【讨论】:

    猜你喜欢
    • 2017-08-15
    • 2017-10-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    相关资源
    最近更新 更多