Get ConnectionString value from app.settings.json file in asp.net core 3.1

Viewed 7406

I am running one asp.net core application version 3.1. Where i have to read connection string value in appsettings.json file. I found many examples related to it, But none of them works for me.

Below are the code used:

appsettings.json file i have provided the connection string value like below:

"ConnectionStrings": {
      "ConnectionString1": "data source=192.xxx.x.xxx; database=MyDatabase; user id=myuser; password=mypass; Pooling=false; Connection Lifetime=10000;"
    }

In Startup.cs file i have the code like below:

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);
            
        }

Now in the controller i have used code like below:

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);
            }
        }

But none of the above code is working to get the connection string value.

Please suggest.

2 Answers

If you want to get ConnectionString in appsettings.js,you can use constructor to get Configuration,And use _configuration.GetSection("xxx").Value or _configuration["xxx"].

Code:

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();
        }
}

result: enter image description here

There is no issue in my code.

There is issue in appsetitngs.json file. According to me it is not an issue. I just change the connection string order and make it to up and after it i am getting the connection string value in application.

Below is the place where i changed the order:

{
  "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": "*"
}

Previously i used this connectionString section just after Logging section.

This might help someone who is struggling for the same.

Related