How to Read Value From appsettings json in .NET core in Controller

How to read/ access value from appsettings.json file in asp.net core 8 mvc using c#.net. Package Microsoft.Extensions.Configuration.Json to read data.
In today's article I will show you a simple tutorial with example how we can access the any configured value in appsettings.json file value in asp.net core 8 mvc application using C#.net in controller. So, for this first we will create a new asp.net core mvc application using c#.net. After creating .net core application open appsettings.json and add the below mention configuration in it. 

 {
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "UserValue": {
        "Value": "This is a test value."
    },
  "AllowedHosts": "*"
} 
In above appsettings.json configuration check the yellow highlighted data. This data we will access at controller end. Before that we will install the Microsoft.Extensions.Configuration.Json NuGet package. This package helps us to get the value form appsettings.json 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

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 userValue = config.GetValue<string>("UserValue:Value");
    ViewBag.UserValue = userValue;
    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. UserValue->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>Value:</b>
	@ViewBag.UserValue
} 
Let's put the break point and check the output.

appsettings.json value at controller
Here we can see that the value added in the appsettings.json we are able to get in controller. Now let's press F5 to check the output.
appsettings.json value in view

Post a Comment