ASP.NET Core SQL Connection TImeout

22,526

Your issue is related to the amount of time it takes for a connection to be established with the server. Altering the CommandTimeout value (the amount of time to allow a command to take to execute) will not have any effect on that. You need to consider increasing the connection timeout value, which is achieved via the connection string:

Server=(localdb)\mssqllocaldb;Database=yourDb;Trusted_connection=true;connect timeout=100;
Share:
22,526
John Oerter
Author by

John Oerter

Updated on September 14, 2020

Comments

  • John Oerter
    John Oerter over 3 years

    I've been working on upgrading an ASP.NET 5 RC1 app to ASP.NET Core 1. I have successfully upgraded it by replacing packages (AspNet to AspNetCore) and changing from EF7 to EF Core (Microsoft.Data.Entity to Microsoft.EntityFrameworkCore).

    The issue I'm having is an intermittent SqlException for Connection Timeout Expired.

    Here is the complete exception:

    System.Data.SqlClient.SqlException occurred.  
    Class=11 ErrorCode=-2146232060 HResult=-2146232060 LineNumber=0  
    **Message=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=924; handshake=6;**   
      Number=-2   
      Procedure=""  
      Server=(localdb)\mssqllocaldb  
      Source=.Net SqlClient Data Provider  
      State=0  
      StackTrace:  
           at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)  
    

    I have tried increasing the command timeout like so:

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
        this.Database.SetCommandTimeout(120);
    }
    

    The exception is thrown on this line, but when I comment it out it will happen elsewhere which leads me to believe it happens the first time the database is accessed.

    app.ApplicationServices.GetService<ApplicationDbContext>().Database.Migrate();