SQL Server connection issue from .Net Core Web API

Smith, Sean 1 Reputation point
2021-06-10T11:28:07.667+00:00

Hi All,

I'm having a really frustrating issue trying to get a connection to SQL Server to work from within a .Net Core (3.1) Web API. I'm using Visual Studio 2019 to develop this in.

So in the appsettings.json file I have

"ConnectionStrings": {
"Test": "Server=ctcdev4;Database=testDB;User ID=testuser;Password=test123"
}

In the actual connection code I have something like this

_connString = _configuration.GetConnectionString("Test");

        SqlConnection conn = new SqlConnection(_connString);
        SqlCommand cmd;
        SqlParameter countParameter;
        string treatmentArm = "";

        try
        {
            // Open connection and perform any tasks
            conn.Open();

            // Create a new command object and set the stored proc name and connection object
            cmd = new SqlCommand("spCheckHoTTrialArm", conn);

            // Set the command type to stored procedure
            cmd.CommandType = CommandType.StoredProcedure;

            // Add an input parameter that will pass the job title to check for
            cmd.Parameters.Add(new SqlParameter("@TrialNo", "A01-001"));

            // Create another paramater to hold the number of matches found
            countParameter = new SqlParameter("@TreatmentArm", SqlDbType.VarChar, 128);

            // Make sure we set the direction of the parameter to output
            countParameter.Direction = ParameterDirection.Output;

            // Add the parameter to the parameters collection
            cmd.Parameters.Add(countParameter);

            // Execute the Command
            cmd.ExecuteNonQuery();

            // Find out whether any matches were found
            treatmentArm = cmd.Parameters["@TreatmentArm"].Value.ToString();
        }
        catch (Exception e)
        {
            return e.ToString();

        }
        finally
        {
            // Close the connection
            if (conn != null)
            {
                conn.Close();
            }
        }

When this is executed it gets to conn.Open(); and errors out with the following:

System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
---> System.ComponentModel.Win32Exception (5): Access is denied.
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at API.Services.RandomisationService.TestHelloWorldInServiceClass() in T:\Development\Projects\API\Services\RandomisationService.cs:line 127
ClientConnectionId:00000000-0000-0000-0000-000000000000
Error Number:5,State:0,Class:20

I've used a similar connection string in some older .Net web projects and it works fine with no connection issues...

<add name="Test" connectionString="Data Source=ctcdev4;Initial Catalog=testDB;UID=testuser;PWD=test123" providerName="System.Data.SqlClient"/>

Does anyone have any idea what's going on as it's driving me mad!

Thanks

Sean

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,604 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,185 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,964 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,005 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Ken Tucker 5,851 Reputation points
    2021-06-10T11:53:53.437+00:00

    The error is saying it cannot reach the SQL server.

    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible

    Can you ping the server ctcdev4 from the computer you are running the web site? if it is pingable can you connect to the sql server with the sql server management studio?


  2. Duane Arnold 3,211 Reputation points
    2021-06-10T12:14:23.753+00:00

    Either the connectionstring is wrong, or MS SQL Server has not been configured for remote connections along with the firewall running on the machine if program in trying to connect remotely.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.