1

当用户尝试上传对服务器来说太大的文件时,我试图更优雅地出错。但是,当我尝试捕获 Global.asax.cs 中的错误时,它似乎跳过了我的重定向代码。这是我所拥有的核心。

protected void Application_Error(object sender, EventArgs e)
{
   HttpContext.Current.ClearError();
   Response.Redirect("CustomErrors.aspx", false);
   Context.ApplicationInstance.CompleteRequest();
}

我到处寻找的“答案”似乎是为了清除错误,但我已经这样做了。还有什么可能出错的。有任何想法吗?

4

3 回答 3

1

我知道这是一个较旧的线程,但我找到了解决这个问题的方法......

在下面的情况下,Google bot 传递了错误的 URL 字符,我只想重定向到默认值。

捕获错误之后 Server.ClearError(); 然后您可以重定向到您网站上的任何页面。

void Application_Error(object sender, EventArgs e)
{
    //... other code here....

    var Message = ex.Message.ToLower();
    var RootURL = Common.GetAppPathMasterPages() + "default.aspx";

    if (Message.Contains("does not exist") || Message.Contains("potentially dangerous request"))
    {
        Server.ClearError();
        HttpContext.Current.Response.Redirect(RootURL);
        return;
    }    

}

于 2015-01-02T16:56:40.463 回答
0

我刚刚尝试了您的代码,当我在Page_Load()测试页面中引发未处理的错误,然后尝试HttpContext.Current.ClearError()Application_Error()在我收到

发送 HTTP 标头后无法重定向错误

删除这个ClearError()方法,就解决了这个问题。

但是,如果我在页面上的事件中引发事件(即单击按钮),即使调用也可以正常工作HttpContent.Current.ClearError().

我确实注意到的一件事是您在“CustomError.aspx”前面没有“~/”,您可能需要添加它以便无论在哪里引发错误都可以找到该页面。(我想我有多个文件夹并且发生错误,上下文将在当前文件夹中)。

添加自定义错误页面的更好方法是使用必要的配置修改 web.config,这将为您执行重定向。然后,您仍然可以在方法中记录错误(通过 Log4Net 或等效Application_Error()方法)。如果您想在自定义错误页面上显示异常,您可能会发现这个问题很有帮助。

从这个链接

<configuration>
    ...

    <system.web>
        <customErrors mode="RemoteOnly"
                      defaultRedirect="~/ErrorPages/Oops.aspx" />

        ...
    </system.web>
</configuration>
于 2013-12-14T10:16:59.250 回答
0

An alternative is to ensure the following is set.

Response.BufferOutput = true;

This way a response is not sent (including the headers) until the the responce is ready to be sent.

See here.

Server cannot set status after HTTP headers have been sent IIS7.5

于 2013-12-14T10:55:58.177 回答