IAsyncActionFilter return blank page
Asked Answered
O

1

5

I'm trying to implement an IAsyncActionFilter in order to redirect to a Maintenance page if the application is set OnMaintenance in the appsettings.json.

I firstly implemented the ActionFilter as following :

public class MaintenanceFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        string controller = (string)context.RouteData.Values["Controller"];
        string action = (string)context.RouteData.Values["action"];

        if (controller != "States" && action != "Maintenance")
        {
            var cs = context.HttpContext.RequestServices.GetService<IClientService>();

            if (await cs.GetMaintenanceState())
            {
                context.Result = new RedirectToActionResult("Maintenance", "States", null);
            }
        }
    }
}

Basically, it just reads the controller and the action from the RouteData of the request. If the action is not "Maintenance", I ask the API if the application is on Maintenance. If yes, it returns to the "Maintenance" action.

Then, in the Startup.cs, I made the actionfilter global :

services.AddMvc(options =>
{
    options.Filters.Add(new MaintenanceFilter());
});

The actionfilter is working as expected, it redirects to the Maintenance action if the api returns true, else it redirects to the initially requested page.

But the html code returned while always be blank, either if the application is on maintenance or not.

Even if I leave the ActionFilter empty like that :

public class MaintenanceFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        
    }
}

Why does my filter return a blank page ?

Ouzel answered 27/12, 2020 at 18:43 Comment(0)
I
7

You should call await next() at the end of OnActionExecutionAsync, otherwise the actual action is not executed:

public class MaintenanceFilter : IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        string controller = (string)context.RouteData.Values["Controller"];
        string action = (string)context.RouteData.Values["action"];

        if (controller != "States" && action != "Maintenance")
        {
            var cs = context.HttpContext.RequestServices.GetService<IClientService>();

            if (await cs.GetMaintenanceState())
            {
                context.Result = new RedirectToActionResult("Maintenance", "States", null);
            }
        }
    }
    await next(); // this executes the actual action
}
Include answered 27/12, 2020 at 18:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.