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

时间:2019-03-22 15:53:23

标签: function azure connection-string

我制作了一个简单的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}");
        }

}

1 个答案:

答案 0 :(得分:0)

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

注意:使用上述方法时,第一个参数取决于类型。这意味着当连接字符串的类型为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

  

我收到以下错误:ConnectionString属性尚未初始化。

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

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