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...
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With