Reputation: 1107
We are trying to exclude certain controllers from our production code (we expose certain endpoints for API manipulation required by our integrated UI tests)
Have a look at the following snippet, can you see anything fundamentally wrong by following this approach?
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class NonProductionAttribute : ApiExplorerSettingsAttribute, IActionFilter
{
public NonProductionAttribute()
{
IgnoreApi = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == EnvironmentName.Production;
}
public void OnActionExecuted(ActionExecutedContext context) { }
public void OnActionExecuting(ActionExecutingContext context)
{
if (IgnoreApi)
{
context.Result = new NotFoundResult();
}
}
}
So basically we simply decorate the "offending" controller with the NonProduction attribute, I am inheriting from ApiExplorerSettingsAttribute to exclude the controller from generated documentation.
A concern might be the use of the Environment variable, perhaps somehow get it from IHostingEnvironment?
Or would you suggest a completely different alternative(for excluding controllers that is)?
Upvotes: 0
Views: 1324
Reputation: 2706
Move all "TestOnly" MVCControllers and/or ApiControllers to it's own Area. That helps you identify the Test-Only-Code much faster too.
In your AreaRegistration, simply don't register any routes based on the Server / Environment your on.
If you don't specify the Route, asp.net will return a 404 for you.
You could even go that far, to move all your test code to it's own assembly and include this (if required) and don't even build/deploy it on prod. https://blog.longle.io/2012/03/29/building-a-composite-mvc3-application-with-pluggable-areas/
Upvotes: 1