In this article we will discuss Using ConfigurationManager.ConnectionStrings in .Net Core.
Here we will explain how we can read connection string in ASP.NET Core MVC.
Microsoft has replaced ConfigurationManager.ConnectionStrings class of System.Configuration namespace with IConfiguration interface in .Net Core.
Before start this article, please visit our previous article Upload File in ASP.Net Core MVC
What is IConfiguration
- The IConfiguration is an interface for .Net Core.
- The IConfiguration interface need to be injected as dependency in the Controller and then later used throughout the Controller.
- The IConfiguration interface is used to read Settings and Connection Strings from AppSettings.json file.
Namespaces
You will need to import the below namespace to access configuration.
using Microsoft.Extensions.Configuration;
Adding the AppSettings.json file
Right click on the Project in Solution Explorer. Then click Add, then New Item and then choose App Settings File option (shown below) and click Add button.
Reading Connection String from AppSettings.json file using IConfiguration interface
In the below example, the IConfiguration is injected in the Controller and assigned to the private property Configuration.
Then inside the Controller, the Connection String is read from the AppSettings.json file using the GetConnectionString function.
Output
When we run the application we can see the output like below, the connection string value we can get in the controller action method.
</> Find the Source Code in Github
Summary
Post a Comment