Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Controller API Endpoint For Production

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?

like image 770
ΩmegaMan Avatar asked Mar 04 '19 17:03

ΩmegaMan


People also ask

What is the purpose of API controller attribute?

The [ApiController] attribute applies inference rules for the default data sources of action parameters. These rules save you from having to identify binding sources manually by applying attributes to the action parameters.

Are controllers endpoints?

Endpoints are a more specific or peculiar version of a Controller. Rather than rely on a view (such as JSP) to render model data in HTML, an endpoint simply returns the data to be written directly to the body of the response(Similar to doing @ResponseBody in Controller).


1 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()
like image 90
Chris Pratt Avatar answered Oct 04 '22 08:10

Chris Pratt