我目前正在.net核心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"
}
}
}
Startup.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();
}
}
的DbContext
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
public DbSet<CustomerTB> CustomerTB { get; set; }
}
我相信问题出在我appsettings.json的某处,但我找不到它
答案 0 :(得分:12)
您的ConnectionStrings
部分位于Logging
部分内,我不知道您的意思是否相同,但无论如何您可以像这样访问DatabaseConnection
:
var connection = Configuration["Logging:ConnectionStrings:DatabaseConnection"];
答案 1 :(得分:1)
在asp.net core 1.x中,您应该通过ConfigurationBuilder
阅读设置。在Startup.cs
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
它可能与asp.net核心2中的方法相同。