{
"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. 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.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.