Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Reading Values From Appsettings.json In ASP.NET Core

Reading Values From Appsettings.json In ASP.NET Core

Date- Sep 10,2022 Updated Mar 2026 5475 Free Download
appsettingsjson ASPNET Core

Understanding appsettings.json

The appsettings.json file is a key component of ASP.NET Core applications, serving as a central location for configuration settings. This file is typically structured in JSON format, making it easy to read and modify. It can contain various settings, such as connection strings, logging levels, and custom application settings.

A typical appsettings.json file might look like this:

{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "credentials": { "UserName": "Shubham", "Password": "code2night", "Email": "code2night@gmail.com" } }

In this example, we have defined logging levels, allowed hosts for the application, and a credentials section containing user information. This structure allows for easy access and management of configuration settings in your application.

Reading Values From Appsettingsjson In ASPNET Core

Creating a Model Class

To read values from the appsettings.json file, we first need to create a model class that matches the structure of the JSON data. This ensures that the data is deserialized correctly into an object that we can work with in our application.

Here’s how to create a model class for the credentials section:

public class CredSettingsModel { public string UserName { get; set; } public string Password { get; set; } public string Email { get; set; } }

In this class, we define properties for UserName, Password, and Email. The property names must match the keys in the appsettings.json file to ensure proper binding.

Registering the Configuration in Program.cs

Once we have our model class, the next step is to register it in the Program.cs file. This is where we tell ASP.NET Core to bind the configuration section to our model class.

To do this, we use the Configure method from the IServiceCollection interface:

builder.Services.Configure(builder.Configuration.GetSection("credentials"));

This line of code retrieves the credentials section from the configuration and binds it to the CredSettingsModel class. This allows us to inject the configuration values into our controllers or services.

Injecting the Configuration into a Controller

With the configuration registered, we can now inject it into our controllers. This is done using the IOptions interface, which provides a way to access the configured options.

Here’s an example of how to inject the configuration into a controller:

using ConfigrationManager.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using System.Diagnostics; namespace ConfigrationManager.Controllers { public class HomeController : Controller { private readonly ILogger _logger; protected readonly IConfiguration _configuration; private readonly CredSettingsModel _credSettingsModel; public HomeController(ILogger logger, IOptions options) { _logger = logger; _credSettingsModel = options.Value; } public IActionResult Index() { string UserName = _credSettingsModel.UserName; string Password = _credSettingsModel.Password; string Email = _credSettingsModel.Email; return View(); } } }

In this example, we inject ILogger and IOptions into the HomeController. The _credSettingsModel variable holds the configuration values, which can be accessed in the Index method.

Using Configuration Values in Views

After successfully injecting the configuration values into the controller, you may want to display them in your views. This can be done by passing the values to the view or using ViewData.

Here’s how you can pass the username to the view:

public IActionResult Index() { string UserName = _credSettingsModel.UserName; ViewData["UserName"] = UserName; return View(); }

In the corresponding view, you can access the username using:

@ViewData["UserName"]

This approach allows for dynamic content rendering based on the configuration values defined in appsettings.json.

Edge Cases & Gotchas

While working with appsettings.json, there are several edge cases and gotchas to be aware of:

  • Missing Configuration Sections: If a section defined in appsettings.json is missing, the application will not throw an error, but the corresponding properties in the model will be null. Make sure to handle such cases to avoid null reference exceptions.
  • Environment-Specific Configurations: ASP.NET Core supports environment-specific appsettings files (e.g., appsettings.Development.json). Ensure that the correct file is being loaded based on the current environment.
  • Data Types: Ensure that the data types in your model class match those in appsettings.json. Mismatches can lead to deserialization issues.

Performance & Best Practices

To ensure optimal performance when working with appsettings.json, consider the following best practices:

  • Use Strongly Typed Configuration: Always use strongly typed classes for configuration settings. This makes your code easier to read and maintain.
  • Limit the Size of appsettings.json: Avoid placing too many settings in appsettings.json. Consider breaking them into smaller configuration files if necessary.
  • Environment Variables: For sensitive information like passwords or API keys, consider using environment variables instead of storing them in appsettings.json.
  • Validate Configuration: Implement validation logic for your configuration settings to catch errors early in the application lifecycle.

Conclusion

In conclusion, reading values from appsettings.json in ASP.NET Core is a straightforward process that enhances the configurability of your applications. By following the steps outlined in this article, you can effectively manage application settings and improve maintainability.

  • Understand the structure of appsettings.json.
  • Create strongly typed model classes for configuration sections.
  • Register configuration in Startup or Program files.
  • Inject configuration into controllers and services using IOptions.
  • Follow best practices for configuration management.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Integrating Entity Framework Core with DB2 in ASP.NET Core Applications
Apr 08, 2026
Mapping Strategies for NHibernate in ASP.NET Core: A Comprehensive Guide
Apr 06, 2026
Performance Tuning NHibernate for ASP.NET Core Applications
Apr 05, 2026
Best Practices for Securing Grok API Integrations in ASP.NET
Apr 04, 2026
Previous in ASP.NET Core
Send SMS using Twillio in Asp.Net
Next in ASP.NET Core
Using Firebase Database in Asp.Net
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,938 views
  • 2
    Error-An error occurred while processing your request in .… 11,272 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 235 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,459 views
  • 5
    Mastering JavaScript Error Handling with Try, Catch, and F… 161 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,497 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,232 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26066 views
  • Exception Handling Asp.Net Core 20797 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20288 views
  • How to implement Paypal in Asp.Net Core 19678 views
  • Task Scheduler in Asp.Net core 17578 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor