【问题标题】:in an Asp.Net core application, Unable to read the connection string from the json file?在 Asp.Net 核心应用程序中,无法从 json 文件中读取连接字符串?
【发布时间】:2018-04-16 19:36:09
【问题描述】:

https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings?

我按照此站点将连接字符串放入 json 文件中,但是当我尝试访问数据库时说我想获取所有酒店的列表时,我收到异常“值不能为空”

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("ConnectionServerJson.json")
        .AddEnvironmentVariables();

    configuration = builder.Build();
}

public IConfiguration configuration { get; set; }

public void ConfigureServices(IServiceCollection services)
{

    services.AddDbContext<DBRezervareHotelieraContext>(options =>
            options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
    services.AddScoped<DbContext>(sp => sp.GetService<DBRezervareHotelieraContext>());
    var container = services.BuildServiceProvider();

    services.AddMvc();
}

这是 connectionStringJson.json 文件

{
  "connectionString": {
    "DefaultConnection": "Server=DESKTOP-TPPITPA\\SQLEXPRESS;Database=DBRezervareHoteliera;Trusted_Connection=True;"
  }
}

我也确实从上下文类 DBRezervareHotelieraContext 中取出了 onConfigure 方法并放入以下内容 公开的

DBRezervareHotelieraContext(DbContextOptions<DBRezervareHotelieraContext> options) : base(options)
{

}

我不认为这很重要,但可能会有所帮助

【问题讨论】:

  • 您已显示 connectionStringJson.json 但您添加的文件(通过 AddJson)是 ConnectionServer Json.json - 错字?
  • 键的正确名称是“ConnectionStrings”,末尾带有“s”。

标签: asp.net-core database-connection


【解决方案1】:

您需要在配置文件中的“ConnectionString”末尾添加一个“s”:ConnectionStrings,并将其命名为 PascalCase。

【讨论】:

    猜你喜欢
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 2019-09-22
    • 2017-07-10
    相关资源
    最近更新 更多