Logo

dev-resources.site

for different kinds of informations.

Individual developer settings in ASP.NET Core

Published at
1/15/2020
Categories
csharp
dotnet
settings
aspnetcore
Author
thomasardal
Categories
4 categories in total
csharp
open
dotnet
open
settings
open
aspnetcore
open
Author
11 person written this
thomasardal
open
Individual developer settings in ASP.NET Core

So, you started using ASP.NET Core and love the new hierarchical JSON-based settings. But now you realize that you need individual settings per developer on your team. In this post, I will show you the best way to achieve just that.

Let's start by looking at settings in ASP.NET Core. You may remember <AppSettings from .NET Full, and luckily, ASP.NET Core (and .NET Core) have a similar construct. In short, you create a new file named appsettings.json and start adding application settings as JSON properties. For the full picture, check out this blog post: AppSettings in ASP.NET Core.

A valid appsettings.json file could look like this:

{
  "AppSettings": {
    "ConnectionString": "http://localhost:9000"
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode

In there, I specified a new object named AppSettings including a single property name ConnectionString with the value of http://localhost:9000. Getting the value from code can either use the full path:

IConfiguration config = ...;
var value = config["AppSettings:ConnectionString"]
Enter fullscreen mode Exit fullscreen mode

Or you can created a strongly typed object representing the AppSettings JSON-object:

public class AppSettings
{
    public string ConnectionString { get; set; }
}

services.Configure<AppSettings>(appSettings);
Enter fullscreen mode Exit fullscreen mode

By calling the Configure-method, you can use dependency injection in ASP.NET Core to inject an AppSettings object into your code.

You now have a hard-coded connection string in your source code, which will end up in a source control system. But what if your code is dependent on a central database with individual users for your developers? The connection string could look something like this:

http://localhost:9000?user=richard&password=1234
Enter fullscreen mode Exit fullscreen mode

The connection string doesn't match a specific database technology, but I'm sure you get the point. The connection string is hard-coded to the user Richard. When Dinesh wants to clone the code and starts developing, he needs to change the setting in appsettings.json.

Environment variables to the rescue. Application settings in .NET Core play very well with environment variables. You can right-click the project, click Properties, select the Debug tab and input a new variable beneath Environment variables:

Notice that the full path is specified with a comma: AppSettings:ConnectionString.

The variable is stored in the launchSettings.json file, located in the Properties folder. This file is under normal circumstances not pushed to source control. In case you want to re-use the key across multiple projects, you can use environment variables built into Windows:

If you are calling the CreateDefaultBuilder-method in your Program.cs file, you are ready to click F5 and launch your project. If not, make sure to call the AddEnvironmentVariables-method:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((ctx, builder) =>
        {
            ...
            builder.AddEnvironmentVariables();
        })
        .UseStartup<Startup>();
Enter fullscreen mode Exit fullscreen mode

If you still want developer settings to be pushed to source control, you can utilize the flexibility of the configuration system in ASP.NET Core, by creating a configuration file per developer machine:

{
  "AppSettings": {
    "ConnectionString": "http://localhost:9000?user=gilfoyle&password=5678"
  }
}
Enter fullscreen mode Exit fullscreen mode

Name this file as the machine it should work on (like appsettings.gilfoyle.json) and make sure to add the following to the Program.cs file:

WebHost.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration((ctx, builder) =>
    {
        ...
        builder.AddJsonFile("appsettings.json", false, true);
        builder.AddJsonFile($"appsettings.{Environment.MachineName}.json", true, true);
    })
    .UseStartup<Startup>();
Enter fullscreen mode Exit fullscreen mode

In the example I tell ASP.NET Core to read settings from the appsettings.json file and override it with any settings in the appsettings.{Environment.MachineName}.json file where {Environment.MachineName} is replaced with the actual machine name on runtime. This way, you can specify an override file per machine.

This post showed you how to specify settings per developer. While the proposed solutions can be excellent for non-secure settings, I don't recommend you to add connection strings and similar to source control. ASP.NET Core offer a feature to overcome this called user secrets. To learn more about this feature, check out our blog post ASP.NET Core (not that secret) User Secrets Explained.

Would your users appreciate fewer errors?

elmah.io is the easy error logging and uptime monitoring service for .NET. Take back control of your errors with support for all .NET web and logging frameworks.

➑️ Error Monitoring for .NET Web Applications ⬅️

This article first appeared on the elmah.io blog at https://blog.elmah.io/individual-developer-settings-in-asp-net-core/

settings Article's
30 articles in total
Favicon
How to Increase the Scrollback Buffer in VSCode Terminal
Favicon
How to Increase the Scrollback Buffer in VSCode Terminal
Favicon
iOS Settings URL's
Favicon
Enhanced Printing Experience Navigating Driver for Your New Printer
Favicon
Tidy Up Your VSCode Explorer with File Nesting
Favicon
RubyMine. How to remove trailing whitespaces
Favicon
Browser: Fetch API Cors settings for server wildcard origin
Favicon
VSCode Settings You Should Use
Favicon
Mac ᄒᅑᆫ글 카보드에ᄉα…₯ 원ᄒα…ͺα„€α…΅α„’α…©( )λ₯Ό ᄇᅒᆨ쿼트(`)둜 λ°”κΎΈλŠ” 방법
Favicon
BEST VSCode Settings for Flutter Developers πŸš€
Favicon
Format C/Cpp files automatically on VS Code
Favicon
πŸ† Default πŸ”— Maven and β˜• Java settings per project
Favicon
Configure the Prettier
Favicon
Configure the ESLint
Favicon
Designing a library for reading layered application settings in Java
Favicon
Using JSON in Angular
Favicon
Techniques to declare settings in a third party Django library
Favicon
Productive Taskbar Settings missing in Windows 11
Favicon
Understand Django: Making Sense Of Settings
Favicon
IntelliJ settings repo
Favicon
GIT Quick Course
Favicon
Fixing My Brave Browser Ads
Favicon
Share stunning Dracula Official VScode Customization
Favicon
πŸ›  Improving the Way You Configure Security Settings in the Auth0 Dashboard
Favicon
Enhance Security in Your .NET Configuration Files
Favicon
Change cursor animation in VSCODE
Favicon
Individual developer settings in ASP.NET Core
Favicon
VSCode good old colors of errors/warnings
Favicon
Introduction of Settings View for Xamarin.Forms
Favicon
Show me your .gitignore

Featured ones: