ActionFilter Response.StatusCode is always 200

为君一笑 提交于 2020-02-22 04:17:19

问题


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...


回答1:


You are looking at the status code of the response before response is actually generated. OnActionExecuting is called before the action is executed, so no status code is set yet. Default value for status code is 200, and that's what you see.

To be able to see the actual status code other actions have assigned to the response, you need to look at OnActionExecuted, which runs after the action.

Update.

Another issue might be the fact that in Core framework action filter runs before and after the action is executed. So the response is not processed yet, and status code is not set in the http response object.

The proper method for your use case seems to be IResultFilter.OnResultExecuted




回答2:


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 }




回答3:


int? statusCode = null;
ObjectResult result = context.Result as ObjectResult;
statusCode = result?.StatusCode;

if (statusCode == null)
{
    StatusCodeResult statusResult = context.Result as StatusCodeResult;
    statusCode = statusResult?.StatusCode;
}


来源:https://stackoverflow.com/questions/50463634/actionfilter-response-statuscode-is-always-200

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!