Forked from GistCF/Connection String Builder For Postgress
Created
December 27, 2022 21:26
-
-
Save caseyspaulding/f48336fec9aef1f4b941d70136c90b53 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ConnectionHelper | |
{ | |
public static string GetConnectionString(IConfiguration configuration) | |
{ | |
var connectionString = configuration.GetConnectionString("DefaultConnection"); | |
var databaseUrl = Environment.GetEnvironmentVariable("DATABASE_URL"); | |
return string.IsNullOrEmpty(databaseUrl) ? connectionString : BuildConnectionString(databaseUrl); | |
} | |
//build the connection string from the environment. i.e. Heroku | |
private static string BuildConnectionString(string databaseUrl) | |
{ | |
var databaseUri = new Uri(databaseUrl); | |
var userInfo = databaseUri.UserInfo.Split(':'); | |
var builder = new NpgsqlConnectionStringBuilder | |
{ | |
Host = databaseUri.Host, | |
Port = databaseUri.Port, | |
Username = userInfo[0], | |
Password = userInfo[1], | |
Database = databaseUri.LocalPath.TrimStart('/'), | |
SslMode = SslMode.Require, | |
TrustServerCertificate = true | |
}; | |
return builder.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment