首页 > 解决方案 > Azure 门户中的 Azure Function Environment.GetEnvironmentVariable 对象引用错误

问题描述

我已使用 Visual Studio 2017 将我的应用程序发布到 Azure Function。由于环境变量中的连接字符串始终为空,我在日志中收到对象引用错误,但是,该应用程序在本地运行良好。下面是我获取连接字符串并记录它的一段代码。

var helper = new Helper();

log.LogInformation($ "The connection string is {helper.GetConnectionString()}");

if (string.IsNullOrWhiteSpace(helper.GetConnectionString())) return req.CreateErrorResponse(HttpStatusCode.BadRequest, "Connection is null");

var signalRService = new SignalRService(helper.GetConnectionString(), helper.GetIotHubName(), log);
log.LogInformation("SignalRService has been initialized");

await signalRService.SendRequest(helper.GetIotHubName(), data?.ToString());
log.LogInformation("SignalRService has been invoked successfully");

return req.CreateResponse(HttpStatusCode.OK, "Success");

下面是我的助手类

public class Helper {
    private static readonly string connectionStringName = "AzureSignalRConnectionString";
    private static readonly string iotHubName = "iotHubName";

    public string GetConnectionString() {
        return Environment.GetEnvironmentVariable(connectionStringName, EnvironmentVariableTarget.Process);
    }
    public string GetIotHubName() {
        return Environment.GetEnvironmentVariable(iotHubName, EnvironmentVariableTarget.Process);
    }
}

当我在门户中监视我的功能时,我可以清楚地看到连接字符串为空。我已经在 local.settings.json 中给出了连接字符串。

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "iotHubName": "iot-hub",
    "AzureSignalRConnectionString": "connection string value",
    "MSDEPLOY_RENAME_LOCKED_FILES": 1
  },
  "Host": {
    "LocalHttpPort": 5181,
    "CORS": "*"
  }
}

我不确定我在这里缺少什么。非常感谢任何帮助。

标签: c#visual-studioazureazure-functionsazure-iot-hub

解决方案


我知道我在这里缺少什么。当涉及到环境变量时,仅将它们添加到 local.settings.json 将无济于事。当我登录到 Azure Function 并检查应用程序设置时,我无法找到我在 local.settings.json 中提供的设置。我做了以下步骤。

  1. 在 Visual Studio 中打开发布设置
  2. 单击管理应用程序设置,我缺少两个环境变量的远程字段中的值。 在此处输入图像描述
  3. 在远程字段中添加值。
  4. 重建和发布函数应用程序
  5. 登录到 Azure 门户并确保值在应用程序设置下。

在此处输入图像描述


推荐阅读