Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionFilter Response.StatusCode is always 200

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 (only) a redirected response?

And why is this not working as is?

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

like image 554
jag Avatar asked May 22 '18 08:05

jag


1 Answers

You can attempt to convert your ActionExecutedContext.Result object to ObjectResult and retrieve StatusCode from it.

public void OnActionExecuted(ActionExecutedContext context)
{
    var statusCode = (context.Result as ObjectResult)?.StatusCode
}
like image 73
Antony Thomas Avatar answered Sep 28 '22 00:09

Antony Thomas