Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Reading Objects From the Config File at Startup

0.00/5 (No votes)
18 Dec 2018 1  
How to deserialize objects from a web applications 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here