Netlify 使用 Blazor WebAssembly 在 C# 上检索环境变量值

问题描述 投票:0回答:1

有谁知道如何从 Netlify 检索环境变量值:https://cli.netlify.com/commands/env/。我有一个网络应用程序只是尝试检索 API 密钥。您可以在 Netlify 上保存 API KEY。我有点迷失,对一个通用问题感到抱歉。有没有人使用 C# 以这种方式完成过某种类型的实现?

c# blazor blazor-webassembly netlify netlify-cli
1个回答
0
投票

您可以创建一种配置 JavaScript 文件,该文件在构建时使用 netlify 的环境变量进行重新水化。首先创建类似 config.js 文件:

window.config = {
    testEnvironmentVariable: "<TEST_ENVIRONMENT_VARIABLE>"
};

还有一个 bash 脚本来替换

config.js
中的每个变量:

#!/bin/bash

# Read the existing content of config.js
content=$(cat wwwroot/config.js)

# Replace the placeholder with the actual environment variable value
updated_content="${content//<TEST_ENVIRONMENT_VARIABLE>/$TEST_ENVIRONMENT_VARIABLE}"

# Write the updated content back to config.js
echo "$updated_content" > wwwroot/config.js

(确保使用

chmod +x update-config.sh
使其可执行)

您的 netlify.toml 文件可能如下所示:

[dev]
  command = "dotnet watch"
[build]
  command = "./update-config.sh && dotnet publish -c Release -o release"
[publish]
  directory = "release/wwwroot"

确保将此

config.js
包含在您的
index.html
文件中:

<head>
    <script src="config.js"></script>
</head>

最后,您可以像这样在 Blazor 中读取这些值:

@code {
    private string? _testEnvironmentVariable;
    protected override async Task OnInitializedAsync()
    {
        var testEnvironmentVariable = await JSRuntime.InvokeAsync<string>("eval", "window.config.testEnvironmentVariable");
        if (testEnvironmentVariable != null)
        {
            _testEnvironmentVariable = testEnvironmentVariable;
        }
    }
}

我是 Blazor 新手,所以也许有一种更简单的方法来做到这一点。

包含所有代码的示例存储库位于:https://github.com/princefishthrower/blazor-netlify-env-injection

我在这里部署了一个示例:https://blazor-netlify-env-injection.netlify.app/

© www.soinside.com 2019 - 2024. All rights reserved.