Blazor 服务器,如果正在开发中如何加载文件[已关闭]

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

我使用 Blazor 服务器 .Net6

当应用程序满足这两个条件时,如何加载特定类型的文件/设置:

  1. ** 开发** 该应用程序仍在开发中。
  2. ** 生产** 应用程序已发布。

在开发阶段,我将连接到测试数据和设置,但在应用程序发布后,我将指向其他数据。

        string = "";
        if (**Development**)
        {
            x = File.ReadAllText("wwwroot/settings/development.json");
        }
        else
        {
            x = File.ReadAllText("wwwroot/settings/production.json");
        }
c# .net server blazor settings
3个回答
1
投票

可以注入

IWebHostEnvironment
接口来查看当前模式。

@inject IWebHostEnvironment _env;


@_currentMode
@code {
    string _currentMode;

    protected override void OnInitialized()
    {
        if (_env.IsDevelopment())
        {
            _currentMode = "dev mode";
        }else if (_env.IsProduction())
        {
            _currentMode = "production mode";
        }
    }
}

1
投票

您需要注射

IWebHostEnvironment
:

@inject IWebHostEnvironment Env
如果在页面中或

[Inject]
public IWebHostEnvironment Env { get; set; }

在后面的代码中。

然后你只需使用

Env.IsDevelopment()
即可返回
bool

在 Stack Overflow 上检查这个类似的问题: 如何从 Blazor 页面访问 env.IsDevelopment()?


1
投票

使用预处理器指令。这是一个简单的例子。

相对于使用

Env.IsDevelopment()
的优势如 Visual Studio 的屏幕截图所示。适用于当前环境的代码块已突出显示。

@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

<div class="alert alert-primary">
@message
</div>

@code {
#if DEBUG
    private string message = "Development";
#else
    private string message = "Production";
#endif
}

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