locked
WebApi - How to restrict the call base on the certain conditions RRS feed

  • Question

  • User1042132515 posted

    I have a requirement to switch on/off some of the features for my application. I am using WebApi and for each feature we have separate controller/class created which contains the WebApi calls for that particular feature.

    When any WebApi call comes to controller I want to check the flag in the DB and base on that flag I want to allow/deny the WebApi call. Any suggestions?

    Admin can on/off feature anytime (after the deployment also). Below is my sample code.

    [RoutePrefix("api/Customer")]
    [Authorize(Roles = "ABC")]
    public class MyController : ApiController
    {
    [HttpPut]
    [Route("{xyz}/abcd")]
    [Authorize(Roles = "ABC")]
    public async Task<IModel> CreateCust(string username)
    {
    }

    [HttpPut]
    [Route("{test}/test")]
    [Authorize(Roles = "ABC")]
    public async Task<IModel> UpdateCust(string username)
    {
    }

    }

    Thanks

    Saturday, July 18, 2015 7:15 AM

Answers

  • User281315223 posted

    You would likely build a custom action filter to handle this and decorate any of the actions within your Controller that you need to apply this logic for. The link that I provided defines how to accomplish this in MVC and the same basic logic applies (i.e. build the filter, decorate your method and determine if the request should or should not go through within the filter) :

    public class CheckDatabaseActionFilter : ActionFilterAttribute, IActionFilter
    {
         public override void OnActionExecuting(ActionExecutingContext filterContext)
         {
              if(CheckYourDatabaseHere())
              {
                    // If the database value is set, don't allow the request (you can also redirect here)
                    filterContext.Result = new EmptyResult();
              }
              else
              {
                    // Otherwise continue as normal
                    base.OnActionExecuting(filterContext);
              }
         }
    }

    Then simply decorate your action or controller with it :

    [CheckDatabase]
    public class MyController : ApiController
    {
    
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, July 18, 2015 10:12 AM