armando t
armando t

Reputation: 159

how configure appsettings.json to have a different connection string from the project when I'm in local

I'm on .NET 5 in an API, and in the appsettings.json I have the following:

The project I'm working on has a connection string like this

"DefaultConnection": "Data Source=someserverAWS.com; initial catalog=ProjectDb; Persist Security Info=True; User Id=lorenz; Password=54321 ; MultipleActiveResultSets=True"

but I don't have access to that server so in order to make the code works for me in local I have to change it every time (I'm working on a new feature for example) to something like this

"DefaultConnection": "Data Source=localhost;initial catalog=ProjectDb;Persist Security Info=True;User Id=sa;Password=12345;MultipleActiveResultSets=True" 

Both are different, so the question is how can I have something on my local that persists when I pull from the repo but doesn't change the repo file when push?

Upvotes: 1

Views: 2503

Answers (2)

Anduin Xue
Anduin Xue

Reputation: 3727

This is simple. Two steps

Step 1. Set your environment variable: ASPNETCORE_ENVIRONMENT

You can add this via the Windows environment variable settings.

Set ASPNETCORE_ENVIRONMENT to Development

enter image description here

Or if usually the launchSettings.json file will be created under the /Properties folder. If you have that file, you can check it that it auto set the environment variable.

enter image description here

Step 2. Copy your appsettings.json to appsettings.Development.json

Now your app will use appsettings.Development.json to override the default appsettings.json file.

You can add your local debugging values in your appsettings.Development.json file.

enter image description here

And now you can edit your connection string.

I strongly suggest you not let git track the development file.

Upvotes: 2

Bertramp
Bertramp

Reputation: 385

Create different appsettings.json for each environment you have.

appsettings.Development.json will be used in debug automatically and appsettings.Production.json will be used automatically in production

appsettings.json is the default fallback file for properties that are not overridden in any specific environment file and for environments that does not have a matching file

Upvotes: 0

Related Questions