【问题标题】:Get ConnectionString value from app.settings.json file in asp.net core 3.1从 asp.net core 3.1 中的 app.settings.json 文件中获取 ConnectionString 值
【发布时间】:2020-10-24 20:22:56
【问题描述】:

我正在运行一个 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);
            }
        }

但以上代码均无法获取连接字符串值。

请提出建议。

【问题讨论】:

  • .SetBasePath(Directory.GetCurrentDirectory()) 可能指向错误的目录。无论如何不要在您的数据库上下文中使用配置,而是使用选项模式
  • 请使用 IConfigurationRoot 提供一些建议,我可以从构造函数调用它来获取连接字符串值,而不是将额外的参数传递给构造函数。
  • 我已经更新了我的问题以获得更多理解,请提供基于它的解决方案。
  • 试试configure GetConnectionString("ConnectionString1")

标签: asp.net-core connection-string


【解决方案1】:

如果要在appsettings.js中获取ConnectionString,可以使用构造函数获取Configuration,并使用_configuration.GetSection("xxx").Value_configuration["xxx"]

代码:

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IConfiguration _configuration;


        public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }

        public IActionResult Index()
        {
            string RedirectUrl = _configuration.GetSection("RedirectUrl").Value;
            return View();
        }
}

结果:

【讨论】:

    【解决方案2】:

    我的代码没有问题。

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

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

    【讨论】:

      猜你喜欢
      • 2020-07-08
      • 2022-06-16
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      相关资源
      最近更新 更多