Christian Schou
  • Casa
  • Blog
    • Programação
      • C#
      • PowerShell
      • Python
      • SQL
    • WordPress
      • Tutoriais
    • Nuvem
    • Automação residencial
      • Assistente Doméstico
        • Node-Red
    • Career
  • Serviços
  • Glossário
  • About
No Result
View All Result
Christian Schou
  • Casa
  • Blog
    • Programação
      • C#
      • PowerShell
      • Python
      • SQL
    • WordPress
      • Tutoriais
    • Nuvem
    • Automação residencial
      • Assistente Doméstico
        • Node-Red
    • Career
  • Serviços
  • Glossário
  • About
No Result
View All Result
Christian Schou
No Result
View All Result
Home Programação C#
individual developer settings

How to configure individual developer settings in .NET Core projects (.NET 6)

by cristã
quarta-feira, dezembro 29, 2021
in C#
0

Recently a reader asked me how I typically manage settings when there is more than one developer assigned to a project. To answer that fast – I use environment variables. In this tutorial, I will show the best way to configure individual developer settings.

I’m sure you know about the hierarchial JSON-based settings handled in appsettings.json. They make up a great solution for configuring global settings for the application, but not when it comes to each individual developer.

If you are ready, then let’s get started configuring some settings. Please notice that I’m using Visual Studio 2022 for this guide, which is the reason why env. variables has been moved.

Tabela de conteúdos
  1. What is appsettings.json?
  2. Configure individual developer settings using environment variables
  3. Multiple configuration files
  4. Summary

What is appsettings.json?

I will make a brief introduction to appsettings.json just to show the difference between that and environment variables. If you are a previously .NET developer, you for sure know <AppSettings> and luckily for you, ASP.NET Core has something similar.

Normally (if not using a template) we would create a new file named appsettings.json and place application settings inside that as JSON properties. The file is simply JSON and is fully tool supported in Visual Studio + Code. This gives us a great way to validate and pretty-print the file using a JSON formatter tool.

A typical normal auto-generated appsettings.json with a connection string would look like the following:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "localhost": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
  }
}

As you can see I have added a ConnectionStrings object with a property named localhost having the value of Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;. At runtime we can get that value from the config with the below code:

IConfiguration config = ...;
var localhost = config["ConnectionStrings.localhost"]

It’s also possible to create a strongly typed object representing the ConnectionStrings JSON object. Start by creating a class and then Configure that as a service, as I have done below:

public class ConnectionStrings
{
    public string localhost { get; set; }
}

services.Configure<ConnectionStrings>(connectionStrings);

When calling the Configure method, we can utilize dependency injection to inject a ConnectionStrings object into our code.

This gives us a hard-coded connection string for our source code and that would end up in a source control system if you are using such things. If you want to, you can read about my favorite GIT commands here. Anyway – what if our code is dependent on a central database where each developer has their own account? Then we have a problem and we are also exposing the credentials for each user… that doesn’t sound good to my ears.

Configure individual developer settings using environment variables

Now that we have a good understanding of how appsettings.json is working and where its limitations are, let’s take a look at environment variables.

Fortunately for us, the application settings in ASP.NET Core go very well hand-in-hand with environment variables. You can click on Debug (top ribbon menu bar) and select <ProjectName> Debug Properties in the menu and see your environment variables in the “Launch Profiles” window.

environment variables visual studio 2022
Environment Variables in Visual Studio 2022

In Visual Studio 2019 this was normally located under Debug in the Properties window for the project and it was also a little easier for beginners to add new variables. Don’t be scared it is still easy to add more variables to a project, it’s just done in another way.

Add a new environment variable with the value of your personal connection string. It could be something like: ConnectionStrings.localhost=Server=myServerAddress;Database=myDataBase;User Id=christian;Password=someRandomPassword;. The new and updated environment variables field would now have the value of ASPNETCORE_ENVIRONMENT=Development,ConnectionStrings.localhost=Server/=myServerAddress;Database/=myDataBase;User Id/=christian;Password/=someRandomPassword;.

The variable is stored inside Properties/launchSettings.json and would in normal circumstances not be submitted with the version control tool. Let’s verify that our new variable was added to that file:

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:4030",
      "sslPort": 44304
    }
  },
  "profiles": {
    "LocalizationAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ConnectionStrings.localhost": "Server=myServerAddress;Database=myDataBase;User Id=christian;Password=someRandomPassword;"
      },
      "applicationUrl": "https://localhost:7013;http://localhost:5013",
      "dotnetRunMessages": true
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

If we take a look at line 18, we can see that the new property and value have been added to the profile. Great!

In .NET 6 we have to use the Environment.GetEnvironmentVariable() method to retrieve the value of an environment variable from the current process:

public static string? GetEnvironmentVariable (ConnectionStrings.localhost);

The above code will at runtime load the connection string from the env. variable and can be used where you need it. Please notice that it is made nullable (“?“) as it might return a null reference.

Multiple configuration files

If the environment variables are not a thing for you and you still want to push the developer settings to the source control, then you can make use of the flexibility in ASP.NET Core. It is actually possible to have a configuration file per developer machine with individual settings, like the one below:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "localhost": "Server=myServerAddress;Database=myDataBase;User Id=christian;Password=someRandomPassword;"
  }
}

For this to work dynamically you would have to name this file the same name as the developer computer name (not the developer – the machine name). It could be something like appsettings.LAPTOP-JR5F9JR.json and then add the following line of code to your Program.cs file just below the other services you already got.

builder.Configuration.AddJsonFile("appsettings.json", false, true);
builder.Configuration.AddJsonFile($"appsettings.{Environment.MachineName}.json", true, true);

What did we just do? In the code above we instruct ASP.NET core to read settings from appsettings.json and override it with the settings in appsettings.{Environment.MachineName}.json where {Environment.MachineName} is replaced at runtime with the actual name of the developer machine. By doing it this way, we can override the files per machine.

Summary

In this short guide/tutorial you learned to configure individual developer settings in a .NET 6 application. The solutions I just taught you are perfect when working with non-secure settings but I would not recommend you to put in connection strings like above. If you need individual connection strings with personal credentials I would recommend you to read my article about user secrets.

If you got any issues, questions, or suggestions, please let me know in the comments. Happy coding! 🙂

Tags: .NET 6.Net CoreappsettingsASP.NET CoreDeveloperDevelopmentSettings
Previous Post

How to add localization in ASP.NET Core Web APIs with Caching

Next Post

What are User Secrets and how to use them in ASP.NET Core

cristã

cristã

Hello 👋 My name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Related Posts

watchdog
ASP.NET Core

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

by cristã
sábado, agosto 13, 2022
0

A reader recently asked me for a more modern way to view log files for requests and exceptions in a...

Read more
restful web api

How to build a RESTful Web API using ASP.NET Core and Entity Framework Core (.NET 6)

segunda-feira, julho 25, 2022
dynamically register entities

How to Dynamically Register Entities in DbContext by Extending ModelBuilder?

sábado, julho 23, 2022
Dockerize ASP.NET Core

How to Compose an ASP.NET Core Web API (.NET 6) with an MS SQL Server 2022 on Linux in Docker

terça-feira, julho 19, 2022
pattern matching in switch

How to do pattern matching in switch statements – C# version >= 7.0

segunda-feira, julho 11, 2022
Next Post
user secrets

What are User Secrets and how to use them in ASP.NET Core

Deixe um comentário Cancelar resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Christian Schou

Christian Schou

Software Developer

Hello - my name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Recent articles

personal website
Career

Top 6 things to add on your personal website to get hired for a tech job

by cristã
domingo, agosto 7, 2022
0

Back in the days before the internet was a thing like it is today, we used to have business cards...

Read more
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

sábado, agosto 13, 2022
get hired for a tech job

5 tips to help you get hired for a tech job

domingo, julho 31, 2022
restful web api

How to build a RESTful Web API using ASP.NET Core and Entity Framework Core (.NET 6)

segunda-feira, julho 25, 2022
dynamically register entities

How to Dynamically Register Entities in DbContext by Extending ModelBuilder?

sábado, julho 23, 2022

Christian Schou

Software Developer

Hello - my name is Christian and I am 26 years old. I'm an educated Software Developer with a primary focus on C#, .NET Core, Python, and PowerShell. Currently, I'm expanding my skills in Software Robots and Cloud Architecture. In some of my spare time, I share my knowledge about tech stuff on my blog.

Recent articles

personal website

Top 6 things to add on your personal website to get hired for a tech job

domingo, agosto 7, 2022
watchdog

The #1 guide to show real-time .NET 6 logs for Web Apps and APIs in a modern way using WatchDog for Free

sábado, agosto 13, 2022
get hired for a tech job

5 tips to help you get hired for a tech job

domingo, julho 31, 2022
  • pt_BRPortuguês do Brasil
    • da_DKDansk
    • en_USEnglish
    • de_DEDeutsch
    • hi_INहिन्दी
  • Contact
  • Política de privacidade
  • Termos de serviço

© 2022 Christian Schou - All rights reserved.

No Result
View All Result
  • Casa
  • Blog
    • Programação
      • C#
      • PowerShell
      • Python
      • SQL
    • WordPress
      • Tutoriais
    • Nuvem
    • Automação residencial
      • Assistente Doméstico
    • Career
  • Serviços
  • Glossário
  • About

© 2022 Christian Schou - All rights reserved.

Eu uso cookies no meu site para lhe dar a experiência mais relevante, lembrando suas preferências e visitas repetidas. Ao clicar em “Aceitar”, você concorda com o uso de TODOS os cookies.
Não vender minhas informações pessoais.
Configurações de cookiesACCEPT
Política de Privacidade e Cookies

Visão geral da privacidade

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Sempre ativado
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
CookieDuraçãoDescrição
__gads1 year 24 daysThe __gads cookie, set by Google, is stored under DoubleClick domain and tracks the number of times users see an advert, measures the success of the campaign and calculates its revenue. This cookie can only be read from the domain they are set on and will not track any data while browsing through other sites.
_ga2 yearsThe _ga cookie, installed by Google Analytics, calculates visitor, session and campaign data and also keeps track of site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognize unique visitors.
_ga_0J2F6JVWSD2 yearsThis cookie is installed by Google Analytics.
_gat_gtag_UA_84232734_11 minuteSet by Google to distinguish users.
_gid1 dayInstalled by Google Analytics, _gid cookie stores information on how visitors use a website, while also creating an analytics report of the website's performance. Some of the data that are collected include the number of visitors, their source, and the pages they visit anonymously.
YouTube2 yearsYouTube sets this cookie via embedded youtube-videos and registers anonymous statistical data. I embed YouTube videos in my articles/tutorials - you won't get the full experience of the articles if this is deactivated.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
CookieDuraçãoDescrição
IDE1 year 24 daysGoogle DoubleClick IDE cookies are used to store information about how the user uses the website to present them with relevant ads and according to the user profile.
test_cookie15 minutesThe test_cookie is set by doubleclick.net and is used to determine if the user's browser supports cookies.
VISITOR_INFO1_LIVE5 months 27 daysA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.
YSCsessionYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.
yt-remote-connected-devicesneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
yt-remote-device-idneverYouTube sets this cookie to store the video preferences of the user using embedded YouTube video.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SALVAR E ACEITAR
Desenvolvido por CookieYes Logo