C# – ConfigurationSection.Get() returns null

When you use ConfigurationSection.Get() to load an object from appsettings.json, it returns null if the section doesn’t exist. Since you’re probably not expecting this to be null, this can lead to problems surfacing in unexpected places, such as getting a NullReferenceException: Note: If you’re using ASP.NET Core, you’ll be referring to the config via builder.Configuration … Read more

ConfigurationBuilder SetBasePath() / AddJsonFile() are missing

If you’re trying to use ConfigurationBuilder to read from appsettings.json, you probably have the following code snippet and are running into compiler errors: This has three different errors, but the compiler only shows you one error at a time. This is due to the way this is designed – ConfigurationBuilder is in one library and … Read more

C# – How to programmatically update the User Secrets file

User Secrets are stored in secrets.json. This file is specific to your application. Once you know the path of secrets.json, you can load and update it. Here’s an example of how to update secrets.json programmatically: Note: 1) For brevity, this isn’t showing all using statements. 2) This is using Newtonsoft because it’s better than System.Text.Json … Read more

Logging to the database with ASP.NET Core

I was reading about logging in ASP.NET when I came across this statement about logging to the database: When logging to SQL Server, don’t do so directly. Instead, add log messages to an in-memory queue and have a background worker dequeue and insert data to SQL Server. Paraphrased from Microsoft – No asynchronous logger methods … Read more

ASP.NET Core – How to turn off startup logging

When you launch an ASP.NET Core web app, you may see the following startup logging messages: These messages come from having a console logger. This logger gets added by default. There are two simple ways to get rid of these logging messages: I’ll show both options below. Option 1 – Turn off logging in appsettings.json … Read more

How to add User Secrets in a .NET Core console app

The User Secrets feature in .NET is a safe, simple way to override values in appsettings.json. The overridden values only exist in a file sitting in your own dev environment, so you don’t accidently commit them to your source control repository. This feature is enabled in ASP.NET by default, and the framework does most of … Read more

C# – How to read configuration from appsettings.json

The appsettings.json file is a convenient way to store and retrieve your application’s configuration. You can add it to any project and then use the Microsoft.Extensions.Configuration library to work with it. Since appsettings.json is just a JSON file, you can add any section / values you want (this is easier than working with XML-based app.config … Read more