繁体   English   中英

在无服务器 C# 中访问环境变量

[英]Accessing Environment variables in Serverless C#

我正在研究与 C# 一起运行的无服务器项目。 我从这个repo 创建了样板代码。 所以我的问题是如何访问serverless.yml文件中提到的环境变量以在方法中使用。 我的serverless.yml文件看起来像这样。

service: doc-header

provider:
  name: aws
  runtime: dotnetcore3.1
  environment: 
    MONGODB_URL: ${ssm:/mongoUrl/${self:provider.stage}~true}

package:
  individually: true

functions:
  docHeaderUpdator:
    handler: AwsDotnetCsharp::AwsDotnetCsharp.Handler::TestFunction
    package:
      artifact: bin/release/netcoreapp3.1/hello.zip
    events:
      - sqs:
          arn: 
            Fn::GetAtt:
              - TestUserQueue
              - Arn
          batchSize: 10
          maximumBatchingWindow: 10

resources:
  Resources:
    TestUserQueue:
      Type: "AWS::SQS::Queue"
      Properties:
        QueueName: "TestUserQueue-${opt:stage,self:provider.stage}"
        FifoQueue: true
        VisibilityTimeout: 200
        MessageRetentionPeriod: 102800
        ReceiveMessageWaitTimeSeconds: 5

我试过使用,

var mongoUrl = Environment.GetEnvironmentVariable("MONGODB_URL");

但似乎不起作用。

正如Martin Costello在评论中解释的那样,Lambda 测试工具 3.1 无法识别 serverless.yml 设置的环境变量,即使它无法识别本地设备中设置的本地环境变量。 如果将其部署到 AWS,然后serverless.yml可以将环境变量应用到 Lambda 运行时,就像普通的 NodeJS 运行时一样。

如果您还需要在本地环境中使用环境变量进行测试,而无需使用相同的代码编写任何其他代码,

var mongoUrl = Environment.GetEnvironmentVariable("MONGODB_URL");

执行。 所以在我的例子中,我使用 VSCode 作为调试环境,所以我可以通过将此部分添加到您的launch.json文件来设置环境变量。

"env": {         
   "MongoDBUrl": "url"       
},

完全launch.json将如下所示。

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": ".NET Core Launch (console)",
      "type": "coreclr",
      "request": "launch",
      "preLaunchTask": "build",
      "program": "/Users/sandunn/.dotnet/tools/dotnet-lambda-test-tool-3.1",
      // More information:
      // https://github.com/aws/aws-lambda-dotnet/tree/master/Tools/LambdaTestTool#configure-for-visual-studio-code,
      // https://github.com/aws/aws-lambda-dotnet/tree/master/Tools/LambdaTestTool#configure-for-visual-studio-for-mac
      "args": [],
      "cwd": "${workspaceFolder}",
      "console": "internalConsole",
      "stopAtEntry": false,
      "internalConsoleOptions": "openOnSessionStart",
      // Add your Environment variables here.
      "env": {
        "MongoDBUrl": "url" 
      }
    }
  ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM