我需要创建一些辅助控制器操作和相关视图,我希望能够(有条件地?)在生产中禁用.
一种方法是在RegisterRoutes()体中的特定路径周围使用#ifdef DEBUG pragma,但这根本不灵活.
web.config中的设置也一样好,但我不知道如何解决这个问题.
已建立的“插件”项目如Glimpse或Phil Haack的旧版Route Debugger如何做到这一点?
我宁愿做一些比YAGNI更简单的事……
解决方法
你也可以使用过滤器,例如把这个类扔到某个地方:
public class DebugOnlyAttribute : ActionFilterattribute { public override void OnActionExecuting( ActionExecutingContext filterContext) { #if DEBUG #else filterContext.Result = new HttpNotFoundResult(); #endif } }
然后你就可以直接进入控制器并使用[DebugOnly]装饰你不需要在生产中显示的动作方法(或整个控制器).
您也可以使用filterContext.HttpContext.IsDebuggingEnabled而不是uglier #if DEBUG我只是倾向于使用预编译器指令,因为决定肯定不会采用任何cpu周期.
如果您希望全局过滤器针对几个URL检查所有内容,请将其注册为Global.asax中的全局过滤器:
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new DebugActionFilter()); }
然后你可以检查URL或你想要的任何列表(这里显示的应用程序相对路径):
public class DebugActionFilter : IActionFilter { private List<string> DebugUrls = new List<string> {"~/Home/","~/Debug/"}; public void OnActionExecuting(ActionExecutingContext filterContext) { if (!filterContext.HttpContext.IsDebuggingEnabled && DebugUrls.Contains( filterContext .HttpContext .Request .AppRelativeCurrentExecutionFilePath)) { filterContext.Result = new HttpNotFoundResult(); } } public void OnActionExecuted(ActionExecutedContext filterContext) { } }
原文地址:https://www.jb51.cc/aspnet/245786.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。