1.使用条件编译符#if Debug,当代码被此标签包含时,换到Release调试模式,代码不会被编译,且访问Controller/Action 会返回404
#if DEBUG
/// <summary>
/// 测试
/// </summary>
[AllowAnonymous]
public class TestController : BaseController
{
/// <summary>
/// 测试
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
[EnableDebug]
[EnableHostEnvionment("Development")]
public FuncResult<Test> GetSensitiveData(string data)
{
return new Test() { SensitiveData = data };
}
}
/// <summary>
///
/// </summary>
public class Test
{
/// <summary>
///
/// </summary>
[SensitiveData]
public string SensitiveData { get; set; }
}
#endif
2.使用特性过滤器:特性打在指定Action或者Controller上,内部判断当前是否调试模式返回的数据是自定义格式
引处参考:https://blog.csdn.net/WPwalter/article/details/80933080
// <summary>
/// 调试模式:Debug,Release
/// </summary>
public class EnableDebugAttribute : ActionFilterAttribute
{
private bool isDebug;
/// <summary>
///
/// </summary>
/// <param name="isDebug"></param>
public EnableDebugAttribute(bool isDebug=true)
{
this.isDebug = isDebug;
}
/// <summary>
/// Action开始之前执行
/// </summary>
/// <param name="actionContext"></param>
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
//应用程序启动debug/release模式
var isDebugCurrent = DebuggingProperties.IsDebug;
if (isDebug != isDebugCurrent)
{
actionContext.Result = new JsonResult(FuncResult.Fail("不允许的启动模式(当前:" + (isDebugCurrent ? "Debug" : "Release") + ")"));
}
base.OnActionExecuting(actionContext);
}
/// <summary>
/// 包含在运行时判断编译器编译配置中调试信息相关的属性。
/// </summary>
public static class DebuggingProperties
{
/// <summary>
/// 检查当前正在运行的主程序是否是在 Debug 配置下编译生成的。
/// </summary>
public static bool IsDebug
{
get
{
if (_isDebugMode == null)
{
var assembly = Assembly.GetEntryAssembly();
if (assembly == null)
{
// 由于调用 GetFrames 的 StackTrace 实例没有跳过任何帧,所以 GetFrames() 一定不为 null。
assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
}
var debuggableAttribute = assembly.GetCustomAttribute<DebuggableAttribute>();
_isDebugMode = debuggableAttribute.DebuggingFlags.HasFlag(DebuggableAttribute.DebuggingModes.EnableEditAndContinue);
}
return _isDebugMode.Value;
}
}
private static bool? _isDebugMode;
}
}