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;"
}
}
这是我需要在控制器中获得的唯一值。我真的需要为它创建一个类吗?
答案 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;
}
}