首页 > 解决方案 > 从 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);
            }
        }

但是上面的代码都没有工作来获取连接字符串值。

请建议。

标签: asp.net-coreconnection-string

解决方案


我的代码没有问题。

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 部分。

这可能会帮助正在为此奋斗的人。


推荐阅读