【问题标题】:ActionFilter - Cannot redirect after HTTP headers have been sentActionFilter - 发送 HTTP 标头后无法重定向
【发布时间】:2016-09-28 16:28:55
【问题描述】:

我正在使用以下 ActionFilter 来检查会话变量是否丢失,如果是,它们将被重定向到“选择仓库代码屏幕”......就用户而言,它工作正常...... . 但是每次我通过 ActionFilter 重定向时,ELMAH 都会报告错误(见下面的代码)。

附:然后将此 ActionFilter 属性放在所有其他控制器继承的基本控制器上。

附言没有其他重定向正在进行...此操作过滤器在他们尝试执行的操作之前触发...我一生都无法弄清楚为什么我不断收到此错误。

public class HasWarehouseCodeExpired : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Controller controller = filterContext.Controller as Controller;

        if (controller != null)
        {
            if (SessionHelper.WarehouseCode == null)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "logon", action = "displaywarehouseselection", area = string.Empty }));
            }
        }

        base.OnActionExecuting(filterContext);
    }
}

错误:

System.Web.HttpException (0x80004005):发送 HTTP 标头后无法重定向。 在 System.Web.HttpResponse.Redirect(字符串 url,布尔 endResponse,布尔永久) 在 System.Web.HttpResponseWrapper.Redirect(字符串 url,布尔 endResponse) 在 System.Web.Mvc.RedirectToRouteResult.ExecuteResult(ControllerContext 上下文) 在 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)

【问题讨论】:

    标签: c# asp.net-mvc-4 redirect


    【解决方案1】:

    好吧,我仍然不知道为什么会发生错误,但是我通过添加以下内容停止了错误:

    filterContext.HttpContext.Server.ClearError();

    像这样:

    if (SessionHelper.WarehouseCode == null)
    {
        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "logon", action = "displaywarehouseselection", area = string.Empty }));
        filterContext.HttpContext.Server.ClearError();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-24
      • 2023-03-27
      • 2014-06-10
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      相关资源
      最近更新 更多