Get data from appsettings.json file

I will show how to get your data from appsettings.json and e.g. show it on view.

First, go to an appsettings.json and add the entry. In my case, I added:
“Message”: “Message from appsettings.json”

All appsettings.json code looks like this:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Message": "Message from appsettings.json"
}
appsettings.json

Second step, changes to the controller, let’s take a sample HomeController.

So inject IConfiguration in HomeController constructor, assign to _config field and add ‘using Microsoft.Extensions.Configuration;’

HomeController code:

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

namespace WebApplicationTest.Controllers
{
    public class HomeController : Controller
    {
        private readonly IConfiguration _config;

        public HomeController(IConfiguration config)
        {
            _config = config;
        }

        public IActionResult Index()
        {
            ViewData["Message1"] = _config["Message"];
            // or
            ViewData["Message2"] = _config.GetSection("Message").Value;

            return View();
        }
    }
}
HomeController.cs

For example, we can use ViewData to assign data from appsettings.json in Index() method:
ViewData[“Message1”] = _config[“Message”];
or
ViewData[“Message2”] = _config.GetSection(“Message”).Value;

public IActionResult Index()
{
    ViewData["Message1"] = _config["Message"];
    // or
    ViewData["Message2"] = _config.GetSection("Message").Value;

    return View();
}
Index() method

And last part – View:

Just add this lines to the view (Index.cshtml):
@ViewData[“Message1”]
@ViewData[“Message2”]

<div>@ViewData["Message1"]</div>
<div>@ViewData["Message2"]</div>
Index.cshtml

Run application to see result:

WebApplicationTest

That’s all 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: