从.NET Core 2中的类读取appsettings.json

Jho*_*iaz 14 c# appsettings asp.net-core-2.0

我需要从业务类的appsettings.json文件(section :)中读取属性列表placeto,但我无法访问它们.我需要将这些属性公之于众.

我在Program课堂上添加文件:

课程

这是我的appsettings.json:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "placeto": {
    "login": "fsdfsdfsfddfdfdfdf",
    "trankey": "sdfsdfsdfsdfsdf"
  }
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*eeb 15

第一:使用默认值,program.cs因为它已添加配置:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}
Run Code Online (Sandbox Code Playgroud)

第二步:为您的类创建一个接口,并通过创建Iconfiguration字段传递依赖注入的配置:

private readonly IConfiguration Configuration;
Run Code Online (Sandbox Code Playgroud)

然后通过构造函数传递它:

public Test(IConfiguration configuration)
{
    Configuration = configuration;
}
Run Code Online (Sandbox Code Playgroud)

然后为您的类创建一个接口,以便Dependency Injection正确使用.然后可以创建它的实例而无需传递IConfiguration给它.

这是类和接口:

using Microsoft.Extensions.Configuration;

namespace GetUserIdAsyncNullExample
{
    public interface ITest { void Method(); }

    public class Test : ITest
    {
        public Test(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        private readonly IConfiguration Configuration;
        public void Method()
        {
            string here = Configuration["placeto:login"];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

第三:然后在您的startup.cs中通过调用以下方法为您的类实现依赖注入:

services.AddSingleton< ITest, Test>();
Run Code Online (Sandbox Code Playgroud)

在你的ConfigureServices方法

现在,您可以将类实例传递给Dependency Injection使用的任何类.


例如,如果您ExampleController想要使用您的课程,请执行以下操作:

 private readonly ITest _test;

 public ExampleController(ITest test) 
 {
     _test = test;          
 } 
Run Code Online (Sandbox Code Playgroud)

现在你有_test实例可以在控制器的任何地方访问它.