๐Ÿ˜œ

์ญˆ๋‚˜์•„๋น  ๋ธ”๋กœ๊ทธ

JUNA
STUDIO

[ASP.NET] Using JSON Configuration(appsettings.json) in ASP.NET

๋ฐœํ–‰์ผ: Feb, 2025
์กฐํšŒ์ˆ˜: 6
๋‹จ์–ด์ˆ˜: 155

Table of Contents


Introduction

When developing with ASP.NET, the WebApplication builder reads configuration files and provides access via the ConfigurationManager class. Typically, developers do not manually read and deserialize JSON configuration files into custom classes.

For small configuration files, direct access is manageable. However, when configurations become more complex with multiple properties, mapping them to a class improves maintainability and readability.


Accessing JSON Values

Consider the following appsettings.json file:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "MyConfig": {
    "Host": "localhost",
    "Port": 4500
  }
}

To retrieve the values for Host and Port, you would use the following code:

var host = builder.Configuration["MyConfig:Host"];
var port = int.Parse(builder.Configuration["MyConfig:Port"]);

Mapping Configuration to a Class

Instead of accessing individual values directly, you can define a class and map the configuration section to an instance of that class:

public class MyConfig
{
    public string Host { get; set; }
    public int Port { get; set; }
}

Then, retrieve the configuration as an instance of MyConfig:

using Newtonsoft.Json.Linq;

var myconfig = builder.Configuration.GetSection("MyConfig").Get<MyConfig>();

var host = myconfig.Host;
var port = myconfig.Port;

Benefits of Using Encapsulated Instances

When dealing with configurations that have numerous properties or nested structures, using a mapped class simplifies management and improves maintainability.


Tags: #ASP.NET#ConfigurationManager#appsettings.json#JSON Configuration#Dependency Injection#.NET Core#WebApplication Builder
JUNA BLOG VISITORS
Today
7
 (
updown
-7
)
Total
657
 (
updown
+7
)

ยฉ 2025 juniyunapapa@gmail.com.