Retrieving appSettings.json data into Controller in ASP.NET Core

Sheonarayan
Posted by in ASP.NET Core category on for Intermediate level | Points: 250 | Views : 343 red flag

In this article, we shall learn how to retrieve appSettings.json data into ASP.NET Core Controllers.
Recommendation
Read Using Area in ASP.NET Core before this article.

Introduction

ASP.NET Core has JSON based settings and configuration files. As against config file in ASP.NET, ASP.NET Core instructs to store the database connection strings and other application related settings into appsettings.json file. However, retrieving those settings from appsettings.json is not as easy as it was in ASP.NET. In this article, we shall learn how to retrieve appsettings.json data into controllers.


ASP.NET Core controller injection

As said, it is not that easy to get the appsettings data into controller, there are different ways to do this and I have chosen a simple way to inject IHostingEnvironment into Controller constructor. 

My appsettings.json file looks like below.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-26e8893e-d7c0-4fc6-8aab-29b59971d622;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

Let's see how to retrieve these data into controller. Here is my controller code.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;

public class HomeController : Controller
{
        public IConfigurationRoot Configuration { get; }

        public HomeController(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
               .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IActionResult Index()
        {
            var returnString = new System.Text.StringBuilder();

            var connStr = Configuration.GetConnectionString("DefaultConnection");
            returnString.Append("<b>ConnectionStrings > DefaultConnection:</b> " + connStr + "<br />");

            var log = Configuration.GetSection("Logging");
            var scope = log.GetValue<string>("Logging > IncludeScopes");
            returnString.Append("<b>IncludeScopes:</b>" + scope + "<br />");

            var defaultLogLevel = Configuration.GetSection("Logging:LogLevel").GetValue<string>("Default");
            returnString.Append("<b>Logging > LogLevel > Default:</b>" + defaultLogLevel + "<br />");

            ViewBag.ConnStr = returnString.ToString();

            return View();
        }
  }
First create a property of type IConfigurationRoot named Configuration as shown above. Inside the controller constructor, set the Configuration property as shown below. Remember to inject the IHostingEnvironment into the controller constructor (If you do not know dependency injection, read here. This code is basically the copy-paste of Startup constructor fro ~/Startup.cs file.

Now let's see how to retrieve the appsettings.json file values. Create an action method and write code as shown below.

public IActionResult Index()
        {
            var returnString = new System.Text.StringBuilder();

            var connStr = Configuration.GetConnectionString("DefaultConnection");
            returnString.Append("<b>ConnectionStrings > DefaultConnection:</b> " + connStr + "<br />");

            var log = Configuration.GetSection("Logging");
            var scope = log.GetValue<string>("Logging > IncludeScopes");
            returnString.Append("<b>IncludeScopes:</b>" + scope + "<br />");

            var defaultLogLevel = Configuration.GetSection("Logging:LogLevel").GetValue<string>("Default");
            returnString.Append("<b>Logging > LogLevel > Default:</b>" + defaultLogLevel + "<br />");

            ViewBag.ConnStr = returnString.ToString();

            return View();
        }
To get the connectionStrings, use GetConnectionString method of Configuration object by passing the ConnectionStrings key.

var returnString = new System.Text.StringBuilder();

var connStr = Configuration.GetConnectionString("DefaultConnection");
returnString.Append("<b>ConnectionStrings > DefaultConnection:</b> " + connStr + "<br />");
To get other section data for which a dedicated method is not exposed (like above) on Configuration object, we need to first retrieve the section using GetSection method and then use GetValue method as shown below.

var log = Configuration.GetSection("Logging");
var scope = log.GetValue<string>("IncludeScopes");
returnString.Append("<b>Logging > IncludeScopes:</b>" + scope + "<br />");
Finally to get the value of nested sections value, use section separator characters ":" as shown below. Notice "Logging:LogLevel" in GetSection method.

var defaultLogLevel = Configuration.GetSection("Logging:LogLevel").GetValue<string>("Default");
returnString.Append("<b>Logging > LogLevel > Default:</b>" + defaultLogLevel + "<br />");

Conclusion

Hope this article was informative and useful as well. Thanks for reading. Do write your feedback or comments below.
Recommendation
Read Implementing simple custom captcha in ASP.NET MVC after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)