Techiehook Techiehook
Updated date Jun 24, 2024
This article provides how to read configuration settings from the appsettings.json file in ASP.NET Core .NET 8.

Download File(s):

AppSettingExample.rar

Read appsettings.json file in ASP.NET Core .NET 8

In ASP.NET Core .NET 8, you can read configuration settings from the appsettings.json file using the built-in configuration system/manager. 

Please follow the below steps to create the project.

  • Create the ASP.NET Core Web API via Visual Studio 2022
  • Check appsettings.json file is present if not add the file.

Appsettings.json file

Your appsettings.json file in your project looks like below. 

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  }  
  "AllowedHosts": "*"
}

Please add the below sample setting to your appsettings.json file,

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "MySettings": {
    "Url": "https://techiehook.com",
    "UserName": "techihook",
    "Password": "pass1234",
    "SerialNumber": "123-456-789-123"
  },
  "AllowedHosts": "*"
}

Bind configuration to a class:

We will create a class that matches the structure of your settings in appsettings.json. For example:

namespace AppSettingExample
{
    public class MyAppSettings
    {
        public string Url { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string SerialNumber { get; set; }
    }
}

Register the class:

We will register the MyAppSettings class with the dependency injection container in Program.cs.

using AppSettingExample;
using System.Runtime;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Add this line to your program.cs
builder.Services.Configure<MyAppSettings>(builder.Configuration.GetSection("MySettings"));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Inject and use the settings in a controller:

We will create a controller called SettingsController.cs and add the Get() method to read the settings from the appsettings.json file as shown below,

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Runtime;

namespace AppSettingExample.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class SettingsController : ControllerBase
    {
        private readonly MyAppSettings _mySettings;

        public SettingsController(IOptions<MyAppSettings> mySettings)
        {
            _mySettings = mySettings.Value;
        }

        [HttpGet(Name = "GetSettings")]
        public IActionResult Get()
        {
            return Ok(_mySettings);
        }
    }
}

Run the application and see the output:

When we run the application, the application reads the configuration settings in appsettings.json file and map the each value in the MyAppSettings class and display it as shown below,

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!