Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save caseyspaulding/f48336fec9aef1f4b941d70136c90b53 to your computer and use it in GitHub Desktop.
Save caseyspaulding/f48336fec9aef1f4b941d70136c90b53 to your computer and use it in GitHub Desktop.
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