Non production .Net Core API

Credit: Free photo 90033051 © publicdomainstockphotos – Dreamstime.com

In many places that I have worked, there was a need to expose API for testing or building up certain data in non production environment.

One way to do so, is add a project that is not part of the production pipeline.

Another way is to mark certain routes as ‘non production’ routes.

The way we can do that, is to add a custom action filter to determine which environment is allowed:

 public class NonProductionActionFilter : ActionFilterAttribute
    {
        private IHostingEnvironment HostingEnv { get; }
        public NonProductionActionFilter(IHostingEnvironment hostingEnv)
        {
            HostingEnv = hostingEnv;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (HostingEnv.IsProduction())
            {
                context.Result = new NotFoundResult();
                return;
            }

            base.OnActionExecuting(context);
        }
    }

And now we can use this attribute to decorate a controller or a route:

 [TypeFilter(typeof(NonProductionActionFilter))]
    [Route("utilities")]
    [Produces("application/json")]
    public class UtilitiesController : Controller
    {
        ....
    }

And now our Utility controller is only accessible in our QA/Staing/Local environments.