首页 > 解决方案 > Blazor:管理环境特定变量

问题描述

如何管理客户端 blazor 中不同环境的访问变量?通常,由于我使用 Azure 发布应用程序,我会使用该appsettings.json文件进行本地应用程序设置,然后在我的应用程序服务的 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 的方式来做到这一点?

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

解决方案


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

.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>

启动.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;

或者看这个问题


推荐阅读