gpt4 book ai didi

function - 应用程序设置中的 Azure Functions v2 连接字符串

转载 作者:行者123 更新时间:2023-12-05 09:13:54 27 4
gpt4 key购买 nike

我制作了一个简单的 Azure Functions v2 Web 服务,它连接到 Azure SQL 数据库,运行具有 3 个参数的存储过程,并将结果作为 JSON 输出返回。它的工作方式与现在一样(使用 run.csx 文件中的连接字符串)。

但是我如何才能从应用程序设置中获取连接字符串?

我在这里和其他地方尝试过各种指南。但我能找到的只是一长串引用文献和一大堆我需要添加的代码。我已严格按照指南进行操作(还在应用程序设置中设置了值),但它不起作用。我对 C# 相当陌生,所以可能我只是不明白我应该做什么。

无论如何,据我所知,这是我的代码和建议的修复:

#r "Newtonsoft.Json"
#r "System.Data"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;

public static async Task<ActionResult> Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");

string login = req.Query["login"];
string pwd = req.Query["password"];
string TransID = req.Query["TransID"];

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
login = login ?? data?.login;
pwd = pwd ?? data?.password;
TransID = TransID ?? data?.TransID;

var cnnString = "Server=MyServer;Database=WebServices;User Id=MyUser;Password=MyPassword;Encrypt=True;";

try
{
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(cnnString);
SqlCommand cmd = new SqlCommand("sp_GetRegRW", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Login", login));
cmd.Parameters.Add(new SqlParameter("@Password", pwd));
cmd.Parameters.Add(new SqlParameter("@TransID", TransID));
await connection.OpenAsync();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(table);
}

return (ActionResult)new OkObjectResult(JsonConvert.SerializeObject(table));
}
catch (SqlException sqlex)
{
return (ActionResult)new OkObjectResult($"The following SqlException happened: {sqlex.Message}");
}
catch (Exception ex)
{
return (ActionResult)new OkObjectResult($"The following Exception happened: {ex.Message}");
}

}

建议的解决方案:

#r "Newtonsoft.Json"
#r "System.Data"
#r "Microsoft.Extensions.Configuration"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;

public static async Task<ActionResult> Run(HttpRequest req, ILogger log, ExecutionContext context)
{
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();

var cnnString =config.GetConnectionString("connWS");
var setting1 = config["Setting1"];

log.LogInformation(cnnString);
log.LogInformation(setting1);
log.LogInformation("C# HTTP trigger function processed a request.");

string login = req.Query["login"];
string pwd = req.Query["password"];
string TransID = req.Query["TransID"];

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
login = login ?? data?.login;
pwd = pwd ?? data?.password;
TransID = TransID ?? data?.TransID;

try
{
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(cnnString);
SqlCommand cmd = new SqlCommand("sp_GetRegRW", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@Login", login));
cmd.Parameters.Add(new SqlParameter("@Password", pwd));
cmd.Parameters.Add(new SqlParameter("@TransID", TransID));
await connection.OpenAsync();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(table);
}

return (ActionResult)new OkObjectResult(JsonConvert.SerializeObject(table));
}
catch (SqlException sqlex)
{
return (ActionResult)new OkObjectResult($"The following SqlException happened: {sqlex.Message}");
}
catch (Exception ex)
{
return (ActionResult)new OkObjectResult($"The following Exception happened: {ex.Message}");
}

}

最佳答案

在函数 v2 中,您应该使用 Environment.GetEnvironmentVariable("string_name",EnvironmentVariableTarget.Process) 从应用程序设置和连接字符串中获取值。

注意:使用上述方法时,第一个参数取决于Type。这意味着当连接字符串的类型为SQLAZURE时,第一个参数应为SQLAZURE + CONNSTR + _stringName

截图如下:enter image description here

代码示例:

//for connection string
string connStr = Environment.GetEnvironmentVariable("SQLAZURECONNSTR_sqldb_connection",EnvironmentVariableTarget.Process);
log.LogInformation("the connection string is: " + connStr);

结果快照:

enter image description here

I get the following error: The ConnectionString property has not been initialized.

您可能应该使用您的连接字符串创建一个 SqlConnection 实例,并在尝试执行任何命令之前打开此连接。

SqlConnection con = new SqlConnection("connStr");
await con.OpenAsync();

关于function - 应用程序设置中的 Azure Functions v2 连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55303414/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com