【问题标题】:Configuration manager can't get connection string in ASP.net 5配置管理器无法在 ASP.net 5 中获取连接字符串
【发布时间】:2016-08-29 02:30:07
【问题描述】:

我有一个 ASP.NET 5 Web 应用程序,它引入了一个 .NET 4.6 类库。在类库中的某个时刻,会调用从 web.config 获取连接字符串:

ConfigurationManager.ConnectionStrings["AppDataConnectionString"].ConnectionString

(注意:我无法更改此代码。)

此类库已用于旧的 Web 表单应用程序,其中 AppDataConnectionString 在其 web.configs 中定义。现在我正在尝试在我的 ASP.NET 5 Web 应用程序中使用类库,但是上面的代码会引发空引用异常。

这是我在 ASP.NET 5 项目中的 web.config 中的连接字符串部分:

<connectionStrings>    
    <add name="AppDataConnectionString" connectionString="server=xxxxxx;database=yyyyy;Trusted_Connection=yes;" providerName="System.Data.SqlClient" />
</connectionStrings>

我也尝试将其添加到 appsettings.json 文件中,如下所示:

{
  "ConnectionStrings": {
    "AppDataConnectionString": {
      "ConnectionString": "server=xxxxx;database=yyyyy;Trusted_Connection=yes;"
    }
  }
}

这里是我在 Startup 中加载配置的地方:

public IConfiguration _Configuration { get; set; }

public Startup()
{
    _Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(provider => _Configuration);             
}

public void Configure(IApplicationBuilder app)
{
    // Call some code from the class library that tries to get that connection string.
}

在我看来,配置管理器只是找不到连接字符串的位置。我的 web.config 或 appsettings.json 的结构是否正确,以便它找到它?

【问题讨论】:

    标签: c# json connection-string asp.net5


    【解决方案1】:

    事实证明,以前在 ASP.net 的早期版本中存储在 web.config 文件中的任何配置现在都需要存储在与 ASP.net 5.0 中的 project.json 相同的目录中的 app.config 文件中.现在我导入的类库可以获取它们的连接字符串并且一切正常。

    【讨论】:

      猜你喜欢
      • 2011-03-20
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      相关资源
      最近更新 更多