Header add

In this article we will discuss Read Connection String from AppSettings.json file in ASP.Net Core MVC.

Here we will explain how we can read connection string in ASP.NET Core MVC.

Microsoft has replaced System.Configuration class with IConfiguration interface in .Net Core 2.0.

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.
Read Connection String from AppSettings.json file in ASP.Net Core MVC

Adding the connection string into AppSettings.json file


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.

Post a Comment

Previous Post Next Post