.NET Backend Get Noticed 2017

How to keep settings in ASP.NET Core?

I’m not a big enthusiast of hard-coded values in my apps, mostly because of three things. First, it’s really annoying to change their value if necessary (especially if one is used in many places). Of course, we can use some „find and replace tool” but to be honest I don’t fully trust them. Another thing is that in many cases we have absolutely no idea what do they represent. Let’s say we have the following of code:

 


PaymentService.Create(order, "1267899567");

 

What does the second parameter represent? Is that some API key, client secret for hashing, or maybe it’s an invoice number? Who knows. Last disadvantage of such approach is that changing the hard-coded value requires all the code (or more precisely, assembly wich contains changed code) to be recompiled before deploying to the server. We can’t simply change and save it. That’s why I’d suggest using always some sort of configuration file. Fortunately doing that with ASP.NET Core is really simple to configure and use! And that’s what I’m going to present right now 馃檪

 

Configuring ASP.NET Core app

Let’s say that we’d like to extract some payment data to the configuration file. The data would be:

  • SecretKey (string)
  • ClientId (int)

The C# class created for that purpose looks as follows:

 


public class PaymnetSettings
{
    public string SecretKey { get; set; }

    public int ClientId { get; set; }
}

 

Now, or the first step is to create a dedicated section inside the appsettings.json file with values:

 


{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "PaymentSettings": {
    "SecretKey": "It's super secret!",
    "ClientId":  "2675"
  }
}

 

Having this we can now move to the Startup class or our application. Inside ConfigureServices method we need to add the following line:

 


services.Configure<PaymnetSettings>(Configuration.GetSection("PaymentSettings"));

 

Believe or not – that’s all we need to do! Having the model registered we can now inject it inside some class. I’ll do this inside default WebAPI ValueController:

 


[Route("api/[controller]")]
public class ValuesController : Controller
{

    public ValuesController(IOptions<PaymnetSettings> settings)
    {
        var paymentSettings = settings.Value;
    }
    
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

 

 

Notice that the only difference is that we had to inject PaymentSettings wrapped by IOptions interface. Comparing to the hard-coded values, this one has a lot of advantages:

  • changing the value requires the action only in one place
  • those values are naturally encapsulated and named inside dedicated classes, so it’s much easier to understand their meaning
  • we can change the value of each parameter having the app running on the server without the need to redeploying it

Hope, that it will help some of you in the future 馃槈

  • Pingback: dotnetomaniak.pl()

  • Nick Foster

    It’s certainly a good place to start and well explained.
    The extra step is to learn about the secret manager and utilising environment variables rather than storing your password / api key in your app settings file which will be committed to source control.
    Have a read of the docs at https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets

  • Just… no[1]. For most of the example settings either environment variables, a secure service, or enough environment variables to connect to a service, or other environment pki in place for such communications.

    Stop putting your settings in config files for service applications… if it’s something that runs on a desktop, sure. If it’s a server app, don’t do it.

    [1] https://12factor.net/

    • I’d say that it depends on how important your environment variables are. If it’s some URL to online payment provider’s API you can put in as described, since it’s already published in docs… Of course passwords, RSA keys etc. should be stored in more secured places rather than plain text in appsettings.json

  • 艁ukasz Arciszewski

    And it’s another way. You can create special settings file with secret values and ignore this file in repository. I describe this way in my blog https://duszekmestre.github.io/dsp2017/2017/04/06/konfiguracja-w-aspnet-core/ (Polish).

  • Milen Rashkov

    Just an FYI: Typo in first code excerpt – PaymentSettings

Don’t miss new posts!

If you enjoy reading my blog, follow me on Twitter or leave a like on Facebook. It costs nothing and will let you be up to date with new posts 馃檪