ActionFilter Response.StatusCode始终为200 [英] ActionFilter Response.StatusCode is always 200

查看:253
本文介绍了ActionFilter Response.StatusCode始终为200的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个动作过滤器,该过滤器仅在HttpContext.ResponseStatusCode为302时才会执行某些操作.

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

我希望能够在OnActionExecuting方法中执行此操作,但是StatusCode始终为200.

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

ActionFilter代码:

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

我的Action方法:

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

并在startup中注册ActionFilter:

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

我已经在浏览器中签入,并且它正确返回302并进行了重定向.我也尝试过使用IAsyncActionFilter界面,但是有同样的问题.

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.

如何将我的ActionFilter应用于(仅 )重定向响应?

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

推荐答案

在实际生成响应之前,您正在查看响应的状态代码. OnActionExecuting在执行操作之前被调用,因此尚未设置状态代码. 默认值状态码是200,那就是您所看到的.

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.

要查看其他操作已分配给响应的实际状态代码,您需要查看OnActionExecuted,该

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.

更新.

另一个问题可能是,在Core框架中,动作过滤器在执行动作之前和之后运行.因此,响应尚未处理,并且http响应对象中的状态代码尚未设置.

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.

适合您的用例的方法似乎是 IResultFilter.OnResultExecuted

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

这篇关于ActionFilter Response.StatusCode始终为200的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆