如何在.NET MAUI中查找当前环境是否为development
?在我的Blazor WASM中,我只需执行以下操作:
builder.HostEnvironment.IsDevelopment()
但是在MauiAppBuilder
中,我没有看到任何环境属性。
如何在.NET MAUI中查找当前环境是否为development
?在我的Blazor WASM中,我只需执行以下操作:
builder.HostEnvironment.IsDevelopment()
但是在MauiAppBuilder
中,我没有看到任何环境属性。
对于这个问题,我通常使用if指令来解决。
例如,如果我想要在发布版本和调试版本中为变量设置不同的值,我会像下面这样做:
#if DEBUG
var a = "debug";
#elif RELEASE
var a = "release"
#endif
祝你好运,希望这有所帮助
目前我找到的唯一有效方法是手动设置变量。在Windows中,我设置了一个用户环境变量 ASPNETCORE_ENVIRONMENT=Development
,然后通过以下方式访问它:
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
MobileHostEnvironment
:internal sealed class MobileHostEnvironment : IHostEnvironment
{
public string EnvironmentName { get; set; } = Environments.Development;
public string ApplicationName { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public string ContentRootPath { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public IFileProvider ContentRootFileProvider { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
}
MauiProgram.cs
的开头,我声明并初始化它,如下所示:private static readonly MobileHostEnvironment _mobileHostEnvironment = new()
{
EnvironmentName = Environments.Production
};
using Microsoft.Extensions.Hosting;
。#if DEBUG
_mobileHostEnvironment.EnvironmentName = Environments.Development;
#endif
这样,调试中的应用程序始终是开发环境,发布的应用程序始终是生产环境。
当然,您可以通过将其注册到依赖容器中来改进此流程。
Environment.SetEnvironmentVariable("name", "value");
- undefined