I need to create some helper controller actions and associated views, that I'd like to be able to (conditionally?) disable in production.
One way would be #ifdef DEBUG
pragmas around the particular routes in the RegisterRoutes()
body, but that's not flexible at all.
A setting in web.config would be just as good, but I'm not sure how to hook that up.
How do the established "plugin" projects like Glimpse or Phil Haack's older Route Debugger do it?
I'd rather do something simple than something YAGNI...
You could also use a filter, eg throw this class somewhere:
public class DebugOnlyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(
ActionExecutingContext filterContext)
{
#if DEBUG
#else
filterContext.Result = new HttpNotFoundResult();
#endif
}
}
Then you'd be able to just drop into the controller and decorate the action methods (or entire controllers) you need not to show up in production with [DebugOnly]
.
You could also use filterContext.HttpContext.IsDebuggingEnabled
instead of the uglier #if DEBUG
I'd just be inclined to use the precompiler directive since the decision is definitely not going to take any CPU cycle that way.
If instead you want a global filter to check everything against a few URLs, register it as a global filter in Global.asax:
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new DebugActionFilter());
}
Then you can just check the URL or whatever you want against the list (App-relative path shown here):
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)
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With