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