我目前正在 .net core 2.0 中创建 Web Api,但我无法让我的连接字符串正常工作。
我已将连接字符串放入 appsettings.json 并将其加载到 startup.cs
Appsettings.json
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"DatabaseConnection": "Data Source=VMDEVSLN-EOE\\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True"
}
}
}
启动.cs
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var connection = Configuration.GetConnectionString("DatabaseConnection");
services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(connection));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
数据库上下文
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
public DbSet<CustomerTB> CustomerTB { get; set; }
}
我认为问题出在我的 appsettings.json 中的某处,但我就是找不到它
最佳答案
您的 ConnectionStrings
部分在 Logging
部分内,我不知道这是否是您的意思,但无论如何您都可以访问 DatabaseConnection
像这样:
var connection = Configuration["Logging:ConnectionStrings:DatabaseConnection"];
关于c# - .Net Core 无法从 appsettings.json 读取连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45862447/