9

What is a recommended way to allow a restful endpoint api or even a controller to be exposed in Development but upon publishing to other environments it is not made available?

Cœur
  • 37,241
  • 25
  • 195
  • 267
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122

2 Answers2

24

There is no built-in way to do this. You'd have to do something like inject IHostingEnvironment into your controller and then do a check like the following in your action:

if (!env.IsDevelopment())
{
    return NotFound();
}

That would then give the appearance that the route didn't actually exist outside of the development environment. If you're going to be doing this enough, it would probably actually be better to create a custom resource filter that you could apply:

public class DevelopmentOnlyAttribute : Attribute, IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        var env = context.HttpContext.RequestServices.GetService<IHostingEnvironment>();
        if (!env.IsDevelopment())
        {
            context.Result = new NotFoundResult();
        }
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
    }
}

Which you could then apply to the relevant actions like:

[DevelopmentOnly]
public IActionResult Foo()
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
1

One can also set the controller action (or the full controller) behind a feature flag, enable it in the Development environment and keep it disable in the Production environment util the feature/endpoint is ready.

  1. Install Microsoft.FeatureManagement.AspNetCore NuGet package
  2. Declare your feature flags in appsettings.json or another config source
{"FeatureManagement": {
        "FeatureA": true, // Feature flag set to on
        "FeatureB": false, // Feature flag set to off
    }
}
  1. Configure DI service builder.Services.AddFeatureManagement();
  2. Decorate controller action (or full controller)

At controller level:

using Microsoft.FeatureManagement.Mvc;

[FeatureGate("FeatureA")]
public class HomeController : Controller
{
    ...
}

At controller action level:

using Microsoft.FeatureManagement.Mvc;

[FeatureGate("FeatureA")]
public IActionResult Index()
{
    return View();
}

See Tutorial for using feature flags in a .NET app | Microsoft Learn

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
eRunner
  • 1,710
  • 1
  • 11
  • 11