Conditionally disable ASP.NET MVC Controller

后端 未结 3 892
终归单人心
终归单人心 2020-12-11 15:22

What is the best way to disable ASP.NET MVC controller conditionally?

I want to have an access to the controller actions if some value in web.config is \"true\" and

相关标签:
3条回答
  • 2020-12-11 15:42

    Answered here - Prevent ASP.NET Core discovering Controller in separate assembly

    This approach doesn't need filters, and hides controller from swagger etc.

    0 讨论(0)
  • 2020-12-11 15:45

    The easiest would probably be to implement a custom action filter:

    http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs

    You can also conditionally add a route that matches that controller that would result in a 404 being returned.

    0 讨论(0)
  • 2020-12-11 15:48

    Cross posting from: https://stackoverflow.com/a/43044667/257470

    My solution for disabling ApiController controller:

    • Uses WebConfig AppSettings config flag instead of (#if DEBUG)
    • Before method is invoked ExecuteAsync intercepts the invocation and checks feature toggle (feature flag);
    • if feature is disabled, returns HTTP 410 GONE
    • If it's common for many controllers, move the code to controller's base class

    The code:

    public class TestController : ApiController
    {
        public override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
        {
            var featureFlag = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["EnableTest"]);
    
            if (featureFlag == false)
            {
                return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Gone));
            }
    
            return base.ExecuteAsync(controllerContext, cancellationToken);
        }
    
    0 讨论(0)
提交回复
热议问题