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

心已入冬 提交于 2021-02-01 05:16:27

问题


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;

回答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.

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

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

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

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.



来源:https://stackoverflow.com/questions/61644033/net-core-on-azure-cant-connect-to-sql-server-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!