AppSettings in ASP.NET 5

There is a massive amount of change in ASP.NET 5 (for the better), the way we use AppSettings is just one. I’ve been using configinjector (https://github.com/uglybugger/ConfigInjector) for a while now, so thought that this might become redundant with these new changes, but there is still work to be done in my opinion before the framework support is as good.

It uses a json file to store the settings, then a class in C# to load them in too, and you can support multiple files/classes as well, I’m just going to look at an example of one and where they need to do some improvement.

To get it start you need to create a class that will map to the data in the json config file


public class AppSettings
{
public string AdminEmail { get; set; }
public Uri AuthHost { get; set; }
}

The following is the corresponding json file


{

"AppSettings": {
"AdminEmail": "admin@hosted-solutions.com.au",
"AuthHost": "kljkljk"
}
}

Then in startup.cs add the following to load it in for use in DI.


public void ConfigureServices(IServiceCollection services)
{
// Add Application settings to the services container.
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

}

Then it can be used in a controller like this following example


private readonly IOptions<AppSettings> _appSettings;

public AccountController(IOptions<AppSettings> appSettings)

{

_appSettings = appSettings;

}

//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{

var i =_appSettings.Value.AuthHost;

}

Now the issue with the above is that I have added a value into the config file that is not the correct data type.

The property AuthHost is Uri but the data in the JSON file “kljkljk” is not a Uri type.

If i was using configinjector, it would blow up on Application Startup, but using this configuration in ASP.NET 5 it only errors when its first accessed within the controller, the same issues I have with the current use of AppSettings in the ConfigurationManager with the web config. So if someone makes a typo you don’t know until code starts to run taht actually uses it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s