How to connect .Net app to Postges

Hi!
I don’t understand how to connect to postgres cluster.

I deployed a .Net app. Then created pg cluster. After that I attached my app to postgres by using this command:
flyctl postgres attach --app <app-name> <postgres-app-name>
And got the connection string, stored in app secrets:
DATABASE_URL=postgres://app-name:password@hostname:5432/app-name?sslmode=disable
But when I run the deployed app I receive such an error at the webpage:

Error.

An error occurred while processing your request.

Request ID: 00-dbc3f379efb8c9743f8bc8dcd3977e82-3c0bb27ffcc72636-00

Development Mode

Swapping to Development environment will display more detailed information about the error that occurred.

The Development environment shouldn’t be enabled for deployed applications. It can result in displaying sensitive information from exceptions to end users. For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development and restarting the app.

In logs I got this:
System.ArgumentException: Couldn't set postgres:<my connection string> (Parameter '<my connection string>')

What am I doing wrong?

Ok, I’ve found the solution…
The problem is the default connection string, provided by fly.io, doesn’t work for asp.net application. To solve this problem it’s required to parse this string:

//Connection to the database
string connectionString = String.Empty;
if (builder.Environment.IsDevelopment())
    connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
else
{
    // Use connection string provided at runtime by Fly.
    var connUrl = Environment.GetEnvironmentVariable("DATABASE_URL");
    
    // Parse connection URL to connection string for Npgsql
    connUrl = connUrl.Replace("postgres://", string.Empty);
    var pgUserPass = connUrl.Split("@")[0];
    var pgHostPortDb = connUrl.Split("@")[1];
    var pgHostPort = pgHostPortDb.Split("/")[0];
    var pgDb = pgHostPortDb.Split("/")[1];
    var pgUser = pgUserPass.Split(":")[0];
    var pgPass = pgUserPass.Split(":")[1];
    var pgHost = pgHostPort.Split(":")[0];
    var pgPort = pgHostPort.Split(":")[1];
    var updatedHost = pgHost.Replace("flycast", "internal");

    connectionString = $"Server={updatedHost};Port={pgPort};User Id={pgUser};Password={pgPass};Database={pgDb};";
};

From How To to Questions / Help

Added dotnet

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.