Hiding connection strings from public Git using .gitignore


Currently i’m increasing my visisbility on the great and big internet. One thing was to add some hobby projects to my public GIT. The first problem I walked into was that there was a secret detected in my public code. Oh no, I uploaded my MongoDb connection string with username and password to public GIT. I quickly removed the public repository and then tought, how am I gonna tackle this problem.


I’m working with a .NET 5 Solution, but this also should work in .NET Core.


You’re code should not already be in git, or else the connection strings can be found in the Git history.


My solution is using a development version of the normal appsettings.json file, named appsettings.Development.json. And hide it using .gitignore.

You can find the appsettings.Development.json blij clicking open the appsettings.json:

Step 1

First you start with adding the following code to the appsettings.json:

    "MongoDbConnectionString": ""

Step 2

Now open the file appsettings.Development.json and add the connection strings with the connection string you want to be hidden from Git:



Please check if the structure of the appsettings.json and the appsettings.Development.json are the same. I had a issue with that the template of both files where not the same.

Step 3

Now create in the root directory a file names .gitignore, or use f.e. this one.

And then add the following lines of code at the bottom:

# Config files

Now you can add you’re sourcecode to GitHub or another public git repository. The appsettings.Development.json will be ignored by GIT and won’t be in youre public repository.


Ofcourse there are other ways to hide your connectionstrings from your public Git repository. F.e. with the user secrets. Maybe I will check this out later and write a blog about that.