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?
2 Answers
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()

- 232,153
- 36
- 385
- 444
-
can't we use @Profile attribute at rest controller and enable it for development? – MathGuy Feb 28 '20 at 20:27
-
I'm not sure what you're talking about. There's no `Profile` attribute. – Chris Pratt Feb 28 '20 at 20:55
-
sorry I mean @Profile annotation at class level. – MathGuy Mar 01 '20 at 00:28
-
Note that `IHostingEnvironment` is deprecated and `IHostEnvironment` should be used instead. [link](https://stackoverflow.com/questions/55601958/ihostingenvironment-is-obsolete) – rhavelka Mar 01 '23 at 04:52
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.
- Install Microsoft.FeatureManagement.AspNetCore NuGet package
- 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
}
}
- Configure DI service
builder.Services.AddFeatureManagement();
- 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