要将连接字符串移动到appsettings.json文件中,需要进行以下更改:
public class MyDbContext : DbContext
{
private readonly IConfiguration _configuration;
public MyDbContext(IConfiguration configuration)
{
_configuration = configuration;
}
// ...
}
public class MyDbContext : DbContext
{
private readonly IConfiguration _configuration;
public MyDbContext(IConfiguration configuration)
{
_configuration = configuration;
}
public string ConnectionString => _configuration.GetConnectionString("DefaultConnection");
// ...
}
{
"ConnectionStrings": {
"DefaultConnection": "Server=myServerAddress;Database=myDatabase;User Id=myUsername;Password=myPassword;"
}
}
public class MyController : Controller
{
private readonly MyDbContext _dbContext;
public MyController(MyDbContext dbContext)
{
_dbContext = dbContext;
}
// ...
}
通过以上步骤,连接字符串就成功地移动到了appsettings.json文件中,使得连接字符串的配置更加灵活和易于管理。
领取专属 10元无门槛券
手把手带您无忧上云