Blazor:管理环境特定的变量

时间:2019-01-31 14:08:02

标签: c# asp.net-core .net-core blazor

如何管理客户端环境中不同环境的访问变量?通常,由于我使用Azure发布应用程序,因此我将使用appsettings.json文件进行本地应用程序设置,然后在App Service的“ Azure应用程序设置”部分中为本地环境和其他环境之间的条目设置条目。

我要完成的示例:

客户端Blazor:

@functions {
    //...more code here
    await Http.PostJsonAsync<object>("http://localhost:50466/api/auth/register", vm);
}

在已部署的Web服务器上,应将其转换为:

@functions {
    //...more code here
    await Http.PostJsonAsync<object>("http://wwww.mywebsite.com/api/auth/register", vm);
}

因此,我正在寻找一种方法来将网站根URL存储在环境变量中,并在发布时对其进行转换。有没有Blazor-ey的方法可以做到这一点?

7 个答案:

答案 0 :(得分:2)

现在,blazor直接支持

appsettings,因此您可以注入它: https://devblogs.microsoft.com/aspnet/blazor-webassembly-3-2-0-preview-3-release-now-available/

答案 1 :(得分:1)

有多种使用方式可以做到这一点,

  

相信,尚无任何官方记录方法!

我的建议是使用良好的旧方法,针对不同的环境使用多个配置文件,并仅复制要在预期环境中使用的配置文件。

在解决方案文件夹中创建一个名为 env 的文件夹。并创建名为 dev prod 的子文件夹。如下所示。

|- env
   |- dev
   |- prod
   |

将不同的配置文件(具有相同名称和不同配置的文件)放置在 dev prod 文件夹中。

创建一个批处理文件以将适当的环境复制到wwwroot文件夹中。 ( 与下一步相比,我更喜欢这样做,因为它非常适合CI, ,无需在构建服务器中安装Visual Studio)

OR

将以下代码添加到 Blazor 项目的post-build event

if $(ConfigurationName) == Debug (
  copy /Y "$(ProjectDir)env\dev\*" "$(TargetDir)\wwwroot"
) ELSE (
  copy /Y "$(ProjectDir)env\prod\*" "$(TargetDir)\wwwroot"
)

由于您的配置文件位于www文件夹中,因此您可以通过打开文件并阅读其中的内容轻松地从blazor应用程序中引用此文件。

答案 2 :(得分:1)

您可以使用配置界面创建单例并将其注入到组件中。

.csproj

<ItemGroup>
   <EmbeddedResource Include="appsettings.Development.json" Condition="'$(Configuration)' == 'Debug'">
     <LogicalName>appsettings.json</LogicalName>
   </EmbeddedResource>
   <EmbeddedResource Include="appsettings.json" Condition="'$(Configuration)' == 'Release'">
      <LogicalName>appsettings.json</LogicalName>
   </EmbeddedResource>
</ItemGroup>

Startup.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(GetConfiguration());
    }

    private IConfiguration GetConfiguration()
    {
        // Get the configuration from embedded dll.
        using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("appsettings.json"))
        using (var reader = new StreamReader(stream))
        {
            return JsonConvert.DeserializeObject<IConfiguration>(reader.ReadToEnd());
        }
    }

MyComponent.razor

@inject Configuration.IConfiguration Configuration;

或者看看这个issue

答案 3 :(得分:1)

我的解决方案是在根项目解决方案中创建3个相应的文件

  • appsettings.json
  • appsettings.Debug.json
  • appsettings.Release.json

然后在项目的 pre-build 事件中将正确的文件替换到 wwwroot 目录

如果$(ConfigurationName)==调试(
复制/ Y“ $(ProjectDir)appsettings.Debug.json” “ $(TargetDir).. \ .. \ .. \ wwwroot \ appsettings.json”

) ELSE(
复制/ Y“ $(ProjectDir)appsettings.Release.json” “ $(TargetDir).. \ .. \ .. \ wwwroot \ appsettings.json” )

答案 4 :(得分:1)

我在所有Blazor网站上都使用了环境变量:

此类EnvironmentVariableHelper是Nuget包DataJuggler.UltimateHelper.Core的一部分

using System;
using System.Collections.Generic;
using System.Text;

namespace DataJuggler.UltimateHelper.Core
{
    public class EnvironmentVariableHelper
    {

        #region Methods

            #region GetEnvironmentVariableValue(string variableName)
            /// <summary>
            /// This method is used to get an environment value
            /// </summary>
            /// <param name="variableName"></param>
            /// <returns></returns>
            public static string GetEnvironmentVariableValue(string variableName)
            {
                // initial value
                string value = "";

                try
                {
                    if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                    {
                        // Change the directory to %WINDIR%
                        value = Environment.GetEnvironmentVariable(variableName, EnvironmentVariableTarget.Machine);
                    }
                }
                catch (Exception error)
                {
                    // for debugging only, do something else with it if you need to
                    DebugHelper.WriteDebugError("GetEnvironmentVariableValue", "GetEnvironmentVariableValue", error);
                }

                // return value
                return value;
            }
            #endregion

        #endregion

    }
}

要创建环境变量,请在Windows 10搜索框中开始键入:

编辑系统环境变量

enter image description here

然后确保将变量添加到底部的系统环境变量(而不是顶部,因为这仅适用于您的用户帐户,将无法使用)。

enter image description here

然后输入变量名称和值,然后单击“确定”。

enter image description here

然后使用它:

string value = EnvironmentVariableHelper.GetEnvironmentVariableValue("Variable Name");

答案 5 :(得分:0)

除了@Kliment Ru的回答之外,还有一种可能性,您可以直接在页面中使用配置文件,而不必将单独的DTO实施为变量所有者:

appsettings.json(您可以使用SlowCheetah创建调试和发布文件并覆盖参数):

{
    "Host": "bla"
}

Startup.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(GetConfiguration());
    }

    public void Configure(IComponentsApplicationBuilder app)
    {
        app.AddComponent<App>("app");
    }

    private IConfiguration GetConfiguration()
    {
        using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("appsettings.json");
        return new ConfigurationBuilder()
            .AddJsonStream(stream) // key method to use, reads JSON stream
            .Build(); // builds the configuration from embedded stream
    }
}

在剃须刀页面中,您拥有:

@page "/Task/list"
@inject HttpClient http
@inject Microsoft.Extensions.Configuration.IConfiguration configuration

...some HTML code

@code {
    private IEnumerable<Model.StoreTask> storeTasks;

    protected override async Task OnInitializedAsync()
    {
        storeTasks = await http.GetJsonAsync<IEnumerable<Model.StoreTask>>(configuration["Host"] + "GetStoreTasks"); // you can use the configuration directly (bla/GetStoreTasks)
    }
}

答案 6 :(得分:0)

在Net Core 3.1和Net 5中,您可以仅在wwwroot中为您的环境创建其他文件:我有wwwroot / appsettings.json;然后在wwwroot中的appsettings.Development.json和appsettings.Production.json。确保在“属性”部分中将它们标记为“如果较新”。他们应该由构建自动拾取。

相关问题