.Net Core Cant从appsettings.json读取连接字符串

Eko*_*kos 1 c# asp.net-mvc json asp.net-core asp.net-core-webapi

我目前正在.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"
  }
 }
}
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

的DbContext

public class DatabaseContext : DbContext
{
    public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
    {

    }
    public DbSet<CustomerTB> CustomerTB { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我相信问题出在我appsettings.json的某处,但我无法找到它

ans*_*erk 11

你的ConnectionStrings部分在该Logging部分内部,我不知道这是不是你的意思,但无论如何你可以访问DatabaseConnection这样的:

var connection = Configuration["Logging:ConnectionStrings:DatabaseConnection"];
Run Code Online (Sandbox Code Playgroud)