Search code examples
c#asp.net-coreaction-filter

ASPNET core. Exclude global filter for a specific Action


I have a global ActionFilter that checks the status of Boolean value and returns to Disabled page if False

       public void OnActionExecuting(ActionExecutingContext context)
        {
           var school = dbcontext.School.Take(1).FirstOrDefault();
            if (school != null)
            {
                // if school status is False, return to Disable page
                if (!school.Status)
                {
                    RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                    redirectTargetDictionary.Add("action", "Disabled");
                    redirectTargetDictionary.Add("controller", "App");
                    redirectTargetDictionary.Add("area", "");
                    context.Result = new RedirectToRouteResult(redirectTargetDictionary);
                    context.Result.ExecuteResultAsync(context);
                }
             }
         }

I have registered this filter to apply to all controller action.

            services.AddControllersWithViews(options =>
            {
                options.Filters.Add(typeof(FeatureFilter));
            });

I have action method that can Change School Status from true to false and false to true.

        [Route("disable")]
        public IActionResult ChangeStatus()
        {
            var school = context.School.FirstOrDefault();
            bool status = school.Status;
            school.Status = !status;
            context.School.Update(school);
            string message = status ? "disabled" : "enabled";
            context.SaveChanges();
            return Json($"Ok this school has been {message} ");

        }

So the problem here I am facing is I cannot change status back to True, since ActionFilter redirects me to Disabled page when School Status is false.


Solution

  • Try to change

    if (!school.Status)
    

    to

    if (!school.Status&&!context.HttpContext.Request.Path.ToString().Equals("/ControllerName/ActionName"))
    

    So that actionfilter will not go to DisabledPage when you call the action.