How to Read Connection String From appsettings json in .NET core in Controller

Ho to read or access connection string value from appsettings.json in file in asp.net core 8 mvc using c#.net at controller class and display in view.
In today's article I will show you a simple tutorial with and example how you can access connection string from appsettings.json file in your asp.net core 8 mvc application at controller end using c#.net. So for this article first we will create a new asp.net core mvc application or .net core 8 and add the connection string in appsettings.json files.

 {
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "ConnectionStrings": {
        "Value": "server=SQLServer;userid=sa;password=123456789;"
    },
  "AllowedHosts": "*"
} 
Refer the above ConnectionString. Note this is a test connection string. Here you can place your own ConnectionString. Here we are having two item key and the value. Before proceeding first we need to install Microsoft.Extensions.Configuration.Json NuGet package. This is used for parsing the xml and used to read the data from XML file.  To install the NuGet package Right click on "Dependencies" and click on Manage NuGet Package. After this a window will open in this window we need to search Microsoft.Extensions.Configuration.Json. Now install the package. 

Microsoft.Extensions.Configuration.Json NuGet package

After installing the package "Microsoft.Extensions.Configuration.Json", we will add a controller class file and add the below code in it. 
[HttpGet]
public IActionResult Index()
{
    var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: false);
    IConfiguration config = builder.Build();
    string con = config.GetValue<string>("ConnectionStrings:Value");
    ViewBag.ConnectionValue = con;
    return View();
} 
In above code I have ConfigurationBuilder builder to read the appsettings.json file json data. After reading the appsettings.json file content. In next line IConfiguration is used to represents a set of key/value application configuration properties of json file. In fila line I have used GetValue to get the value from appsettings.json by using key. ConnectionStrings->Value. At the end I have stored the value to Viewbag to display the value at view. Now lets check the view code.
 @using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
	<span>Data From appsettings.json</span>
	<br />
	<b>Connection String:</b>
	@ViewBag.ConnectionValue
} 
In above code I demonstrated to display the viewbag data to user. Now lets run the code by puttin the breakpoint. 

Connection String

In above code we can see the connection defined in appsettings.json we are able to get at controller end in our asp.ne core mvc application.  Now press F5 to check the output.

View data

Post a Comment