如何以编程方式执行与声明方式相同的操作
在 Azure Functions 的 Web.config 文件中?或者有没有更简单的
在这里使用的方法?
根据我的测试,如果我们想在Azure函数中使用Azure MSI连接Azure SQL,请参考以下步骤:
Create function app project in VS2019
配置 local.setting.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "<your storage connection string>",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
},
"ConnectionStrings": {
"SQLConnectionString": "Server=tcp:<server name>.database.windows.net,1433;Initial Catalog=<db name>;"
}
}
-
Configure MSI for VS
一个。登录 Visual Studio 并使用Tools > Options 打开选项。
b.选择Azure Service Authentication,输入您的 Azure SQL 管理员帐户并选择确定。
开发功能
例如
/* please install sdk :
Install-Package Microsoft.Azure.Services.AppAuthentication -Version 1.3.1
Install-Package System.Data.SqlClient -Version 4.6.1
*/
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string str = "SQLConnectionString";
string conStr = GetSqlAzureConnectionString(str);
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://database.windows.net/");
var conn = new SqlConnection(conStr);
conn.AccessToken = accessToken;
string result = "";
var sql = "select * from StarWars where episode=1";
using (SqlCommand command = new SqlCommand(sql, conn))
{
conn.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read()) {
result = reader.GetString(2);
}
}
}
return new OkObjectResult($"Hello, {result}");
}
private static string GetSqlAzureConnectionString(string SQLConnectionString)
{
string conStr = System.Environment.GetEnvironmentVariable($"ConnectionStrings:{SQLConnectionString}", EnvironmentVariableTarget.Process);
if (string.IsNullOrEmpty(conStr)) // Azure Functions App Service naming convention
conStr = System.Environment.GetEnvironmentVariable($"SQLAZURECONNSTR_{SQLConnectionString}", EnvironmentVariableTarget.Process);
return conStr;
}
- 使用 Visual Studio 调试函数。请注意,我们需要在调试之前安装Azure Functions Core Tools。
另外,如果要调试后发布,请参考以下步骤
- 创建 Azure 函数
Configure MSI for function app
-
配置 Azure SQL
一个。 Use your Azure Sql AD admin to connect Azure SQL vai SSMS
b.将 MSI 添加到您需要使用的数据库中
USE [<db name>]
GO
create user [<function app name>] from external provider
ALTER ROLE db_owner ADD MEMBER [<function app name>]
在 Azure 函数应用程序设置中添加连接字符串
Publish it with Visual Studio