简体   繁体   中英

SQL connection in class library works from .NET 6 web app, fails from source ASP.NET website

We have an older and complex ASP.NET 4.8 site (the 'Web Site' approach, not 'Web Application'). I am creating a new .NET 6 web app that will do some similar functions. I adapted code from the old site into a new class library using .NET Framework 4.8, so we can avoid maintaining duplicate code. The library includes code calling a SQL Server using SqlConnection (not EF).

That library works well with the new .NET 6 app, including the SQL Server calls. But when I pointed the old ASP.NET site at the library, the SQL Server calls fail with the error:

Microsoft.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.

It fails when simply opening the connection, like this:

var sqlConn = new SqlConnection(connectionString);
await sqlConn.OpenAsync();

This is when using EXACTLY the same library as works with the .NET 6 app, running on the same machine (SQL Server is external machine). I verified multiple times that the connection string is exactly the same. I also tested on a different machine.

As a test, I created a very simple new class library calling SQL Server (with hard-coded connection string), and a new ASP.NET 4.8 web site calling that library. That works. I added a new test page within the old ASP.NET web site calling that test library. That fails with the server-not-found error.

As a summary, the problem looks like:

  • .NET 6 web app > .NET 4.8 class library SQL client = OK
  • Test ASP.NET 4.8 web site > .NET 4.8 class library SQL client = OK
  • Full ASP.NET 4.8 web site > .NET 4.8 class library SQL client = Fails

So the problem is not the basics of calling SQL Server using a class library. It must be something else within the old site, but I'm stumped after spending days trying to run down the cause. Suggestions as to what else to look at appreciated.

To circle back on this, I created a new empty ASP.NET website and started added content from the old site. I figured that at some point, I would run into the SQL connection error. I gradually added in content, bit by bit, and testing as I went along. But I added all content, and didn't hit the error, I'm still mystified about what caused the old site to stumble. but at least it works now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM