Skip to content

Instantly share code, notes, and snippets.

@GistCF
Created September 9, 2022 19:33
Show Gist options
  • Save GistCF/4a2e6afdd8fb184c7381d4bb4577ffb4 to your computer and use it in GitHub Desktop.
Save GistCF/4a2e6afdd8fb184c7381d4bb4577ffb4 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();
}
}
@Khaihuyennguyen
Copy link

Where I put this code in for the bugtracker if I develop in .NET 5?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment