72 lines
1.7 KiB
C#
72 lines
1.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace MAX.Core.Helpers;
|
|
|
|
public class EnvironmentHelper
|
|
{
|
|
private static string? _currentEnvironment;
|
|
|
|
// 获取当前环境
|
|
public static string CurrentEnvironment
|
|
{
|
|
get
|
|
{
|
|
if (_currentEnvironment == null)
|
|
{
|
|
_currentEnvironment = DetermineEnvironment();
|
|
}
|
|
return _currentEnvironment;
|
|
}
|
|
}
|
|
public static bool IsTest => CurrentEnvironment.Equals("Test", StringComparison.OrdinalIgnoreCase);
|
|
public static bool IsDevelopment => CurrentEnvironment.Equals("Development", StringComparison.OrdinalIgnoreCase);
|
|
|
|
public static bool IsProduction => CurrentEnvironment.Equals("Production", StringComparison.OrdinalIgnoreCase);
|
|
|
|
private static string DetermineEnvironment()
|
|
{
|
|
#if RELEASE
|
|
// Release 构建:只允许生产环境,不允许其他环境
|
|
return "Production";
|
|
#else
|
|
// 1. 检查环境变量
|
|
var envVar = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ??
|
|
Environment.GetEnvironmentVariable("ENVIRONMENT");
|
|
|
|
if (!string.IsNullOrEmpty(envVar))
|
|
{
|
|
return envVar;
|
|
}
|
|
|
|
|
|
// 检查当前机器名
|
|
string machineName = Environment.MachineName.ToLower();
|
|
if (machineName.Contains("dev") ||
|
|
machineName.Contains("test"))
|
|
{
|
|
return machineName.Contains("TEST") ? "Test" : "Development";
|
|
}
|
|
|
|
// 4. 默认返回 Production
|
|
return "Production";
|
|
#endif
|
|
}
|
|
|
|
// 获取环境描述
|
|
public static string EnvironmentDescription
|
|
{
|
|
get
|
|
{
|
|
if (IsTest) return "测试环境";
|
|
if (IsDevelopment) return "开发环境";
|
|
if (IsProduction) return "生产环境";
|
|
return $"未知环境 ({CurrentEnvironment})";
|
|
}
|
|
}
|
|
}
|