【问题标题】:My issue is "Server cannot set status after HTTP headers have been sent."我的问题是“发送 HTTP 标头后服务器无法设置状态”。
【发布时间】:2015-05-16 17:44:49
【问题描述】:

我收到了一个错误:

((IController)controller).Execute(new RequestContext(new HttpContextWrapper(System.Web.HttpContext.Current), routeData));

System.Web.Mvc.dll 中出现“System.Web.HttpException”类型的异常,但未在用户代码中处理

附加信息:发送 HTTP 标头后服务器无法设置状态。

完整代码如下。

 private void RedirectToControllers(string control, string action, bool redirectCheck = false)
        {
            var routeData = new RouteData();
            routeData.Values["controller"] = control;
            routeData.Values["action"] = action;
            IController controller = null;
            if (control == Constants.Alerts)
            {
                controller = new AlertsController();
            }
            else if (control == Constants.Account)
            {
                controller = new AccountController();
            }

            if (controller != null)
            {
                if (redirectCheck)
                {
                   ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(System.Web.HttpContext.Current), routeData));
                   // new RedirectResult(Constants.LoginUrl, true);
                }
                else
                {
                    string returnUrl = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
                    if (System.Web.HttpContext.Current.Response.RedirectLocation == null)
                    {
                        System.Web.HttpContext.Current.Response.Redirect(string.Format("/{0}/{1}?" + returnUrl, ControllerHelper.Controller.ACCOUNT, ControllerHelper.Controller.Action.ACCOUNT_LOGIN));
                    }
                }
            }
        }

【问题讨论】:

    标签: asp.net-mvc controller asp.net-mvc-5


    【解决方案1】:

    该错误表明您的应用程序中的某些内容正在更改Response.Headers 集合,然后尝试设置状态代码。这不是在您提供的代码块中完成的,而是在您的应用程序的其他地方发生的。

    解决方法是在将请求传递到控制器之前清除请求。你可以通过调用Response.Clear()来做到这一点。

    var httpContext = new HttpContextWrapper(System.Web.HttpContext.Current);
    httpContext.Response.Clear();
    ((IController)controller).Execute(new RequestContext(httpContext, routeData));
    

    您应该检查您的应用程序,以确保这是正确的操作过程,因为这将清除您的应用程序正常运行可能需要的任何其他响应设置。

    【讨论】:

    • 我收到相同代码的错误。 System.Web.Mvc.dll 中发生“System.Web.HttpException”类型的异常,但未在用户代码中处理附加信息:发送 HTTP 标头后服务器无法设置状态。
    • 使用 if (System.Web.HttpContext.Current.Response.RedirectLocation == null) { } 解决的问题
    猜你喜欢
    • 2014-01-27
    • 2011-01-23
    • 2015-11-07
    • 1970-01-01
    • 2019-07-22
    • 2016-08-27
    • 2015-06-24
    • 1970-01-01
    • 2012-09-28
    相关资源
    最近更新 更多