我有一个在 ASP.NET CORE 2.1 中开发的 Web 应用程序。我希望代码在开发和生产模式下表现不同。我试过#if Debug else代码,但这不符合我的要求。
谁能建议我如何在 Program.cs 文件中的 C# 中找到当前模式?
该IWebHostEnvironment接口提供方法IsDevelopment()。只需将其注入到您尝试从中使用它的任何类中即可。
public class MyClass
{
public MyClass(IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
// Run development specific code
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您确实需要从 DI 容器/范围之外访问它,那么理论上您可以读取ASPNETCORE_ENVIRONMENT环境变量的值。请注意,这是一个实现细节,通过这种方式访问它可以绕过框架。
var isDevelopment = string.Equals(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"), "development", StringComparison.InvariantCultureIgnoreCase);
Run Code Online (Sandbox Code Playgroud)