【问题标题】:ActionFilterAttribute not redirectingActionFilterAttribute 不重定向
【发布时间】:2013-08-23 12:11:22
【问题描述】:

我遇到了未正确重定向的 ActionFilterAttriute 问题。我不熟悉完整的代码库,但我看到的足够多,无法理解发生了什么。

为了简化代码,我删除了不相关的部分:

public class ResolveApplicationRedirectAttribute : ActionFilterAttribute
{
    //some variables
    private ActionExecutingContext _filterContext;

    protected string ApplicationRedirectUrl
    {
        get { return ConfigurationManager.AppSettings["ApplicationRedirectUrl"]; }
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        _filterContext = filterContext;

        //a lot of logic that decide if we should redirect or not

        //I added this after the other logic to make it always redirect regardless of what happens inside the logic above
        _filterContext.Result = new RedirectResult(ApplicationRedirectResult);
    }
}

[ResolveApplicationRedirect]
public ActionResult Index(CrmQueryStringParameters crmParameters){
  //some logic
}

这通常是可行的,但是当应用程序在短时间内受到一些请求的影响时,Index 方法最终会被调用,并且因为 View 缺少一些数据而崩溃(我们知道它缺少数据。那这就是我们要重定向的原因)。

但是现在当我将_filterContext.Result = new RedirectResult(ApplicationRedirectResult) 添加为OnActionExecuting 方法的最后一行时,它怎么可能仍然调用我的Action 方法?

是否有任何已知的错误/角落案例/任何其他可能导致 MVC 忽略我已放入 filterContext 并触发操作方法的 RedirectResult

任何可能在 OnActionExecuting 逻辑中的特殊内容,即使我将 filterContext.Result 设置为最后一行也会导致问题。属性内的任何异常都应该直接炸掉,而不是跳过属性调用 Action 方法。

任何能帮助我指明正确方向的人都将在此不胜感激。

【问题讨论】:

  • 如果您查看 MVC 的源代码,您会看到一个方法 InvokeActionMethodFilter,它在您的过滤器上执行 OnActionExecuting,并传递 ActionExecutingContext。如果它返回一个非空的 Result 值,它会返回一个 ActionExecutedContext 跳过调用您的操作。所以,在某种程度上,你所看到的不应该是可能的。因此,唯一的问题可能是 Result 的空值。如果您评论所有逻辑并仅保留最后一行,那么您的重定向是否有效?

标签: .net asp.net-mvc asp.net-mvc-4 actionfilterattribute


【解决方案1】:

+1 表示 Wouter 的结果。鉴于您显示的代码,应该不可能实现您描述的结果。也许// magic logic here 正在返回一个空的_filterContext.Result

【讨论】:

    【解决方案2】:

    我终于找到了问题所在。它与使用_filterContext 类变量有关。

    问题在于MVC不会为每个请求创建一个新的过滤器实例,导致多个请求共享同一个属性实例。

    有关更多详细信息,请参阅重大更改列表in the MVC3 release notes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      • 2019-09-15
      相关资源
      最近更新 更多