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