从appsettings.json中检索配置

时间:2016-08-03 23:06:23

标签: asp.net json asp.net-core asp.net-core-1.0

ASP.NET Core现在使用appsettings.json进行应用程序配置,我只想从以下appsettings.json文件中获取连接字符串:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "ConnectionStrings": {
    "Default": "Server=localhost; Database=mydatabase; Trusted_Connection=True;User id=myuser;Password=mypass;Integrated Security=SSPI;"
  }
}

这是我需要在控制器中获得的唯一值。我真的需要为它创建一个类吗?

1 个答案:

答案 0 :(得分:3)

不,您不必为它创建一个类。您只需使用IConfiguration即可访问ConnectionStrings。简单用法:

public class Startup
{
    private IConfiguration Configuration;

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
           //...;
        Configuration = builder.Build();

        // Get ConnectionString by name
        var defaultConStr = Configuration.GetConnectionString("Default");
    }
    // If you need to resolve IConfiguration in anywhere with dependency injection, below code is required
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IConfiguration>(Configuration);
    }

}

更新评论

public class YourController : Controller
{
    private readonly IConfiguration _config;
    public YourController(IConfiguration config)
    {
        _config = config;
    }
}