0

I have a connection string which uses username and password. However, the credentials are stored as environment variables (I'm using OpenShift), so I would like to add the credentials (username and password) from the code, at runtime.

While I could probably achieve this using reg-ex, or some other creative ideas, it just seems like something that would be supported by default in C#. I found this answer in another post, suggesting to use an EntityConnectionStringBuilder, but this only works for .NET Framework (I'm using .NET Core 3.1). Is there anything similar for .NET Core (or maybe even smarter)?

Also I am using Entity Framework Core, so anything that modifies the connection itself, and not the connection string, is not really an option.

Jakob Busk Sørensen
  • 5,599
  • 7
  • 44
  • 96
  • 1
    https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnectionstringbuilder?view=dotnet-plat-ext-3.1&viewFallbackFrom=netcore-3.1? – CodeCaster Sep 07 '20 at 12:26
  • @CodeCaster so all I had to do was change 'Enity' with 'Sql' :-). Thanks for the tip. If you want credit, please make a answer with a minimum example. If not, I'll make it myself, to help others. – Jakob Busk Sørensen Sep 07 '20 at 12:34
  • Feel free to post your own! – CodeCaster Sep 07 '20 at 13:14

2 Answers2

1

As mentioned by @CodeCaster in the comments - the answer is the SqlConnectionStringBuilder. It allows adding sections, like User ID to an existing connection string. So to add username and password to a connections string from the appsettings.json, you can do something like this:

string baseConnStr = Configuration.GetConnectionString("MyConnectionString");

var builder = new SqlConnectionStringBuilder(baseConnStr);
builder.UserID = "Test";
builder.Password = "Abc123";

var connStr = builder.ConnectionString
Jakob Busk Sørensen
  • 5,599
  • 7
  • 44
  • 96
0

If you have access to the config file something like this might work

<connectionStrings>
<add name="Connection" connectionString="Url=https://smth.com; Username=Username; Password=Password" />
</connectionStrings>

and you just need to access the connection name

Sterben
  • 9
  • 2
  • 2
    The problem is that the username and password only exists in OpenShift (the hosting environment), so it is unknown at compile time. Hence the request for a solution that works at runtime (which `SqlConnectionStringBuilder` does). – Jakob Busk Sørensen Sep 07 '20 at 12:42