asp.net-core - 从 asp.net core 3.1 中的 app.settings.json 文件中获取 ConnectionString 值
问题描述
我正在运行一个 3.1 版的 asp.net 核心应用程序。我必须在 appsettings.json 文件中读取连接字符串值。我发现了很多与之相关的例子,但没有一个对我有用。
以下是使用的代码:
appsettings.json 文件我提供了如下连接字符串值:
"ConnectionStrings": {
"ConnectionString1": "data source=192.xxx.x.xxx; database=MyDatabase; user id=myuser; password=mypass; Pooling=false; Connection Lifetime=10000;"
}
在 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.AddControllers();
services.AddSingleton<IConfiguration>(Configuration);
}
现在在控制器中我使用了如下代码:
IConfiguration configure;
public MyAPIController(IConfiguration _config)
{
configure = _config;
}
public IActionResult GetSummary([FromBody] ReportParameters rp)
{
try
{
var connection = configure.GetValue<string>("ConnectionStrings:ConnectionString1");
var connection1 = configure.GetSection("ConnectionStrings").GetSection("ConnectionString1").Value;
var connection2 = configure["ConnectionStrings:ConnectionString1"];
var connection3 = configure.GetConnectionString("ConnectionString1");
return Ok(SomeValue);
}
catch (Exception ex)
{
return BadRequest(ex.ToString() + Environment.NewLine + "Error Path: " + Request.Path);
}
}
但是上面的代码都没有工作来获取连接字符串值。
请建议。
解决方案
我的代码没有问题。
appsetitngs.json 文件中存在问题。在我看来,这不是问题。我只是更改连接字符串顺序并将其设置为向上,然后我在应用程序中获取连接字符串值。
以下是我更改订单的地方:
{
"ConnectionStrings": {
"ConnectionString1": "data source=192.xxx.x.xxx; database=MyDatabase; user id=myuser; password=myuser; Pooling=false; Connection Lifetime=10000;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
以前我在 Logging 部分之后使用了这个 connectionString 部分。
这可能会帮助正在为此奋斗的人。
推荐阅读
- html - 如何选择正确的元素来应用 CSS(准确地说是 SASS)
- python - 黄昏 ml 逻辑回归抛出此错误:“NotImplementedError: Can not add intercept to array with unknown chunk shape”
- c# - 将不同的 JSON 处理成类属性
- python - Matplotlib 包已安装,但代码不工作
- python - 将 TF-IDF 结果保存到 CSV 文件中
- iframe - 无法在 amp iframe 中加载 html 文件
- javascript - React Bootstrap Table - 尝试用相等的列宽填充页面
- spring-boot - 未找到来自 Maven 依赖项的 spring boot @repository bean
- c++ - Objective C++,如何在后台线程中使用runloop?
- google-bigquery - 优化 BigQuery 查询的费用