c# - .Net Core 无法从 appsettings.json 读取连接字符串

标签 c# json asp.net-mvc asp.net-core asp.net-core-webapi

我目前正在 .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/

相关文章:

c# - 带条件间距的 string.format 效率

c# - .NET 中的文件访问被拒绝

javascript - 即使值确实存在,Jquery 也不附加值

asp.net-mvc - 您自定义数据库IdentityDbContext

c# - 是否可以在 Windows 应用商店应用程序中使用 Chromium Embedded Framework (CEF)

c# - 如何将 Xamarin.Forms 条目绑定(bind)到非字符串类型,例如 Decimal

javascript - 如何准备一个可解析的 json 对象数组?

javascript - 读取 Json 变量

c# - 如何处理 Multi-Tenancy ASP MVC 站点的路径设置

c# - 检查 Controller 和 View 中的权限