我尝试通过执行后续步骤来使用json文件中的连接字符串
Json文件
{
"ConnectionStrings": {
"PlatformDatabase": "Server=xxxx\\SQLEXPRESS;Database=xxxx;Trusted_Connection=True;"
}
}
访问json
var builder = new ConfigurationBuilder()
.SetBasePath(System.AppContext.BaseDirectory)
.AddJsonFile("appsettings.json",
optional: true,
reloadOnChange: true);
Configuration = builder.Build();
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("PlatformDatabase"));
错误: ConfigurationBuilder不包含 AddJsonFile。
以前有人有这个问题吗?我尝试搜索它,但我找到的所有解决方案现在都不起作用(我认为版本2)。
编辑
请注意。我创建了.Net Core 2.0控制台应用程序
答案 0 :(得分:4)
安装nuget包
解决了这个问题Microsoft.Extensions.Configuration.Json
答案 1 :(得分:1)
您无需在ASP.NET Core 2中明确添加appsettings.json
。
您只需要Startup.cs
-
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(
Configuration.GetConnectionString("PlatformDatabase")));
...
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
}
<强> 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();
}
您在 DI容器中将 IConfiguration 注册为 Singleton / strong>,然后将其注入您的DBContext构造函数。然后在OnConfiguring
方法中获取连接字符串。
public class Startup
{
public Startup(IConfiguration config)
{
_config = config;
}
private IConfiguration _config;
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(_config);
services.AddDbContext<YOUR_DB_Context>(ServiceLifetime.Scoped);
...
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
}
}
<强> YOUR_DB_Context.cs 强>
public class YOUR_DB_Context : IdentityDbContext OR DbContext
{
private IConfiguration _config;
public YOUR_DB_Context(DbContextOptions options, IConfiguration config)
: base(options)
{
_config = config;
}
protected override void OnModelCreating(ModelBuilder builder)
{
...
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_config["Data:PlatformDatabase"]);
}
}