ASP.NET Core now uses appsettings.json for the application configuration, i just want to get the connection strings from the following appsettings.json file:
{
"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;"
}
}
That's the only value the I need to get in my controllers. Do I really need to create a class for it?
No, you don't have to create a class for it. You can simply use IConfiguration
to access ConnectionStrings
. Simple usage:
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);
}
}
Update for comment
public class YourController : Controller
{
private readonly IConfiguration _config;
public YourController(IConfiguration config)
{
_config = config;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.