How to read connection string in .NET Core?Ask Questions

 Posted on 09/11/2019

I want to read just a connection string from a configuration file and for this add a file with the name "appsettings.json" to my project and add this content on it:


"ConnectionStrings": {

"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet- WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"


"Logging": {

"IncludeScopes": false, "LogLevel": {

"Default": "Debug", "System": "Information", "Microsoft": "Information"





On ASP.NET I used this:

var temp=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;


Now how can I read "DefaultConnection" in C# and store it on a string variable in .NET Core?


Share On: facebook gplus twitter
Asked by Jhon Walls on 09/11/2019 Score: 64 points
Add Comment:


1 Answers

1 Corrected Answers
Aproved Answers
Answered by hardik chaudhary on 9/11/2019 8:57:33 AM Score: 557 points

The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.

In Startup.cs

public void ConfigureServices(IServiceCollection services)
    // Add the whole configuration object here.

In your controller add a field for the configuration and a parameter for it on a constructor

private readonly IConfiguration configuration;

public HomeController(IConfiguration config) 
    configuration = config;

Now later in your view code you can access it like:

connectionString = configuration.GetConnectionString("DefaultConnection");


Configure is an extension method. It should be used most commonly like this: services.Configure<SmtpConfig>(Configuration.GetSection("Smtp")); Sure, it's much the same thing, but I think people not aware will just start doing it the "wrong" way, using the uncommented line, so perhaps best to remove the line
11/09/2019   09:01:48   Praful Chauhan
Add Comment:

Post Your Answers

Existing Members

Sign in to your account
Email Address
New Member?
Sign up and complete profile
Full Name
Email Address
I have read and agree to the Terms of Service and Privacy Policy
Please subscribe me to the StoodQ newsletters
Guideline to answer a question:

Useful tips to submit your answer
Please read below guidelines before you submit your answer for question.

  • Read and understand question for which you are submitting your answer.
  • Try to avoid grammatical and spell mistake while answering.
  • Do not post any irrelevant information in your answer.
  • Explain your answer with example or any reference link to help who posted question.
  • If you find irrelevant question, please report it to support. Click here to contact support.
  • You agree to the privacy policy and terms of use to submit any contents.

Note: StoodQ is online developers community which helps developer for their difficulty, lets help them with your value contribution.