Marek Schwarz
Marek Schwarz

Reputation: 440

SQL connection over Azure function works only on localhost

I ran azure function over Visual Studio. The function returns some data from SQL database hosted also on Azure (SQL Server), on localhost works everything fine, but when I publish it to the azure, it returns 500 error.

On Azure SQL, I have checked accessing from other Azure services and my IP address.

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": ""
  },
  "ConnectionStrings": {
    "MySqlConnectionString": {
      "ConnectionString":
        "Server=tcp:webappgtoproject.database.windows.net,1433;Initial Catalog=database;Persist Security Info=False;User ID=xxx;Password=yyy;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;",
      "providerName": "System.Data.SqlClient"

    }
  }
}

Code

string str = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString;

using (SqlConnection conn = new SqlConnection(str))
{
    conn.Open();

    // Check PC
    string text2 = "command text";

    using (SqlCommand cmd = new SqlCommand(text2, conn))
    {
    }

    return true;
}

Without that SQL connect it works fine on Azure.

Upvotes: 1

Views: 1198

Answers (1)

Mikhail Shilkov
Mikhail Shilkov

Reputation: 35144

local.settings.json file is only used when running locally. You need to define your connection string in App Settings (click you Function App and select App Settings link).

Upvotes: 3

Related Questions