Search code examples
postgresqlsocketsasp.net-corenpgsqlef-core-3.0

Dotnet core Web API with EF core doesn't connect to PostgreSQL


I have a Web API developed using dotnet core 3.1 and EF core 3.1. I created a postgreSQL Db in IBM cloud and can access the same using PgAdmin. However when i try to connect to db via code i get the following error.

System.Net.Sockets.SocketException: Can't assign requested address at at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName) at at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress) at at System.Net.Sockets.Socket.Bind(EndPoint localEP) at at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketConnectionListener.Bind() at at Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportFactory.BindAsync(EndPoint endpoint, CancellationToken cancellationToken) at at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.<>c__DisplayClass21_0``1.<<StartAsync>g__OnBind|0>d.MoveNext() at at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindEndpointAsync(ListenOptions endpoint, AddressBindContext context) at at Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions.BindAsync(AddressBindContext context) at at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.AddressesStrategy.BindAsync(AddressBindContext context) at at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.AddressBinder.BindAsync(IServerAddressesFeature addresses, KestrelServerOptions serverOptions, ILogger logger, Func2 createBinding) at at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.StartAsync[TContext](IHttpApplication1 application, CancellationToken cancellationToken) at at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken) at at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken) at at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token) at at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token) at at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host) at Marketplace.Api.Program.Main(String[] args) in /Users/jayasuryajeyakodi/my/startup/Marketplace/Marketplace.BackEnd/Marketplace.Api/Program.cs:16

Here is how i have coded in startup.cs

connectionString = "Server=*.databases.appdomain.cloud;Database=*;Port=30331;User Id=ibm_cloud_*;Password=*;

Solution

  • Your error doesn't seem to have anything to do with Npgsql or the database connection. If you examine the stack trace you can see the Npgsql isn't in there, and that the exception is thrown from Socket.Bind as Kestrel is trying to set up your socket transport. There is likely a network configuration issue where you've specified an address to bind/listen on, and that address isn't valid.