Search code examples
c#.net-coresqlconnection

Dot net Core – How to fix: TimeOut-Error to MSSQL 2017 (which does not happen with .Net 4.7.1)


Can't connect to a MS SQL Server 2017 Express from dotnet core 2.2 console application.

Checked Server Configuration as in Connection to SQL Server Works Sometimes

I have installed a new Microsoft SQL Server 2017 Express. Then tested the connection to this server with a console application (under .Net Framework 4.7.1). Works!.

Then I created a console application under Dot Net Core 2.2. Installed NuGet package System.Data.SqlClient and tried connect to the sql server using the same connection string I tested before and got a timeout error. How can this be fixed? (I also used the package Microsoft.Data.SqlClient, with the same result.)

If I try to connect to another SQL-Server (2008) the connection is established without problems.

using System;
using System.Data.SqlClient;

namespace ConsoleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Connecting");

            using (var conn = new SqlConnection(@"server=<IP>\SQLEXPRESS;user id=sa;password=<PASSWORD>;database="))
            {
                Console.WriteLine("Try to open connection");

                conn.Open();

                Console.WriteLine("Connection opened");
            }
            Console.ReadLine();
        }
    }
}

Following Exception occured:

Microsoft.Data.SqlClient.SqlException: 'Connection Timeout Expired.  The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement.  This could be because the pre-login handshake failed or the server was unable to respond back in time.  The duration spent while attempting to connect to this server was - [Pre-Login] initialization=21064; handshake=50; '

Solution

  • Forcing to use named pipes by specifying np: qualifier in the server parameter in the connection string does the job.

    
    Console.WriteLine("Connecting");
    
    using (var conn = new SqlConnection(@"server=np:<IP>\SQLEXPRESS;user id=sa;password=<PASSWORD>;database="))
    {
        Console.WriteLine("Try to open connection");
    
        conn.Open();
    
        Console.WriteLine("Connection opened");
    }
    Console.ReadLine();