65.9K
CodeProject is changing. Read more.
Home

Reading Objects From the Config File at Startup

Dec 18, 2018

CPOL

1 min read

viewsIcon

10187

How to deserialize objects from a web application"s config file

Introduction

This tip reveals a very simple way to read sections of a web application's config file as objects, without requiring the Options pattern or dependency injection.

Background

In ASP.NET Core, it's quite easy to configure a a group of related settings in the config file, normally appsettings.json, to be deserialized as classes and injected into DI clients. It is, however, apparently not as simple to simply deserailize an object from this file and use it before the DI container has been fully initialized.

Using the Code

As an example, I have taken code of mine where I configure password rules for ASP.NET Identity by reading these rules as an object from appsettings.json. Normally, I would hard code these settings, as they seldom change during the lifetime of an application, but in a project where I'm including password generation, and I want generated passwords to conform to the same rules as those configured for Identity, I thought it would be nice to store these password options in appsettings.json.

This is how I store the password rules in the config file:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=Flair;Trusted_Connection=True;
     MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    },
  },
  "Authentication": {
    "PasswordRules": {
      "RequiredLength": 8,
      "RequiredUniqueChars": 2,
      "RequireNonAlphanumeric": false,
      "RequireLowercase": false,
      "RequireUppercase": false,
      "RequireDigit": true
    }
  },
  "AllowedHosts": "*"
}

And this is how I read these settings and configure Identity, in Startup.cs:

var pwdSection = Configuration.GetSection("Authentication:PasswordRules");
var pwdOpts = pwdSection.Get<PasswordOptions>();
services.Configure<IdentityOptions>(options =>
{
    options.Password = pwdOpts;
});

The options.Password property of the IdentityOptions being configured is a simple object of class PasswordOptions. All I have to do is make sure the "Authentication:PasswordRules" section of my config file is a serialization of an object.

The magic happens with the call:

var pwdOpts = pwdSection.Get<PasswordOptions>()

This would not normally be possible, unless I include the following NuGet package in the project.

Microsoft.Extensions.Configuration.Binder

This was kindly revealed by this StackOverflow answer.

History

This is the first version of this tip.