Response.Redirect在Global.asax中不起作用

时间:2013-03-28 10:23:58

标签: asp.net c#-4.0 exception-handling global-asax

我想在应用程序抛出异常时重定向到错误页面,但它不会重定向到该页面。这是我的代码:

protected void Application_Error(object sender, EventArgs e)
    {

        StringBuilder theBody = new StringBuilder();

        Exception exception = Server.GetLastError();

        StackTrace st = new StackTrace(exception, true);
        // Get the top stack frame
        StackFrame frame = st.GetFrame(0);
        // Get the line number from the stack frame
        int line = frame.GetFileLineNumber();

        string file = frame.GetFileName();

        MethodBase site = exception.TargetSite;
        string methodName = site == null ? null : site.Name;

        string type = exception.GetType().ToString();

        theBody.Append("Line: " + line + "<br/>");
        theBody.Append("Method: " + methodName + "<br/>");
        theBody.Append("File: " + methodName + "<br/>");
        theBody.Append("IP: " + Request.ServerVariables["REMOTE_HOST"] + "<br/>");
        theBody.Append("Error Message: " + exception.Message + "<br/>");
        theBody.Append("Error Stack:" + exception.StackTrace);

            Response.Redirect("~/404.aspx", false);
            Context.ApplicationInstance.CompleteRequest();


       ...
    }

我在测试页面上尝试这样做

 try
        {

            throw new Exception("Test exception!!");
        }
        catch (Exception)
        {


        }

它不会重定向404.aspx继续留在测试页面上。我该怎么做才能重定向404.aspx?

1 个答案:

答案 0 :(得分:1)

按照此链接http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/displaying-a-custom-error-page-cs

中的说明在web.config中设置它
<system.web>
        <customErrors mode="On"
                      defaultRedirect="~/ErrorPages/Oops.aspx" />

        ...
    </system.web>