ActionFilter Response.StatusCode is always 200

asked7 years ago
last updated7 years ago
viewed5.8k times
Up Vote13Down Vote

I'm trying to setup an action filter that only does something if the StatusCode of the HttpContext.Response is 302.

I would expect to be able to do this in the OnActionExecuting method, but the StatusCode is always 200.

ActionFilter code:

public class CustomFilter : IActionFilter
{
   public void OnActionExecuting(ActionExecutingContext context)
    {
        // do some setup
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.HttpContext.Response.StatusCode == StatusCodes.Status302Found)
        {
            // never get here
        }
    }
}

My Action method:

public IActionResult Redirect()
{
    return RedirectToAction("Index", "Home");
}

And registering the ActionFilter in startup:

public void ConfigureServices(
    IServiceCollection services)
{
    services.AddMvc(
        options =>
        {
            options.Filters.Add(new CustomFilter());
        });
}

I have checked in the browser and it is correctly returning 302 and doing the redirect. I have also tried using the IAsyncActionFilter interface but had the same problem.

How can I apply my ActionFilter to () a redirected response?

And why is this not working as is?

: Whoops I had them the wrong way round. Actually I am still getting this issue though...