我使用 Blazor 服务器 .Net6
当应用程序满足这两个条件时,如何加载特定类型的文件/设置:
在开发阶段,我将连接到测试数据和设置,但在应用程序发布后,我将指向其他数据。
string = "";
if (**Development**)
{
x = File.ReadAllText("wwwroot/settings/development.json");
}
else
{
x = File.ReadAllText("wwwroot/settings/production.json");
}
可以注入
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";
}
}
}
您需要注射
IWebHostEnvironment
:
@inject IWebHostEnvironment Env
如果在页面中或
[Inject]
public IWebHostEnvironment Env { get; set; }
在后面的代码中。
然后你只需使用
Env.IsDevelopment()
即可返回 bool
。
在 Stack Overflow 上检查这个类似的问题: 如何从 Blazor 页面访问 env.IsDevelopment()?
使用预处理器指令。这是一个简单的例子。
相对于使用
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
}