.NET Core on Azure can't connect to SQL Server Database

1

I have a .NET Core API backend which is published on Azure. I also have a SQL Server database running on Azure, if I run my backend app locally it succesfully connects to the online database, reading/writing etc works fine. When running the online backend however, every API call results in a 500 error. When looking in the logs there is the following error which probably causes the 500:

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. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

So for some reason the backend hosted on Azure does not have access to this database. In the Azure portal of my online db I have added the IP of my backend to firewall exception and "Allow remote Azure connections to server" is checked.

TLDR; everything works fine locally, published version on Azure can't connect to/find database.

Edit: this is resolved, thanks everyone who commented. (special thanks to Jason!) Solution was to use the following format of connection string:

Data Source=tcp:servername.database.windows.net,1433;Initial Catalog=db;Persist Security Info=False;User ID=user;Password=mypassword;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
.net
sql-server
azure
core
asked on Stack Overflow May 6, 2020 by bomeister • edited May 7, 2020 by bomeister

1 Answer

1

UPDATE

I operate according to the tutorial, see the screenshot for detailed steps. The official documentation contains sample code, which you can download and see. I put my conn string in my code.

If you configure your connnection strings in web.config or other files, u can see this document. And u can configure it in your portal.

enter image description here

Step 1. Modify connection strings in code, and add a interface for test.

enter image description here

Step 2. Create a Todo Table for peoject. [Make sure you have finished Firewall setting]

enter image description here

Step 3. Test in local then deploy. You can see my project run successfully and interface can be used.

enter image description here

PRIVIOUS

You can go to your sqldb ,find Connection strings and copied the one provided there.

This string was in the format:

Data Source=tcp:servername.database.windows.net,1433;Initial Catalog=db;
Persist Security Info=False;
User ID=user;Password=mypassword;
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;
Connection Timeout=30;

There also have a post which has the same issue. For more details,u can read it.

answered on Stack Overflow May 7, 2020 by Jason • edited May 7, 2020 by Jason

User contributions licensed under CC BY-SA 3.0