The problem I encountered here was with Host value in the connection string.
When using Host=localhost;Port=5432;... and building the application over Docker Compose from Visual Studio the connection fails with the following error:
Npgsql.NpgsqlException: 'Exception while connecting'
Inner Exception
ExtendedSocketException: Cannot assign requested address [::1]:5432
The solution to the problem is to simply use Host=host.docker.inner;Port=5432;... instead.
But what I do not get is what is actually wrong here. The database indeed runs on localhost:5432 which I confirmed by connecting to it using pgAdmin tool and this exact address as a server URL. I could access the tables, the data, etc.
So why doesn't the connection from ASP.NET Core work?