nnchvxx
nnchvxx

Reputation: 81

Exclude controller depending on environment .NET Core Web Api

I want to exclude a controller from .NET Core Web Api, because it's not ready for production.

I know we can add an attribute, but I am trying to do it runtime depending on the environment from the Startup class.

Is there a way to do it when we register the controllers?

Thank you

Upvotes: 1

Views: 1251

Answers (1)

Brando Zhang
Brando Zhang

Reputation: 27997

According to your description, I suggest you could try to write a custom middleware to achieve your requirement.

At this middleware we could check the request path if this request path contains the path and the environment is the the development then we could directly return the 404.

app.Use(async (context, next) =>
{
    if (env.IsDevelopment()
        && context.Request.Path.Value.Contains("WeatherForecast"))
    {
        context.Response.StatusCode = 404;
        return;
    }
    else
    {
        await next.Invoke();
    }
});

Upvotes: 3

Related Questions