Пример #1
0
        /// <summary>
        /// 全局异常处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(object sender, EventArgs e)
        {
            string            s      = HttpContext.Current.Request.Url.ToString();
            HttpServerUtility server = HttpContext.Current.Server;

            if (server.GetLastError() != null)
            {
                Exception lastError = server.GetLastError();

                // 此处进行异常记录,可以记录到数据库或文本,也可以使用其他日志记录组件。
                ExceptionHander.WriteException(lastError);

                Application["LastError"] = lastError;

                int    statusCode        = HttpContext.Current.Response.StatusCode;
                string exceptionOperator = "/SysSample/Error";

                try
                {
                    if (!string.IsNullOrEmpty(exceptionOperator))
                    {
                        exceptionOperator = new System.Web.UI.Control().ResolveUrl(exceptionOperator);
                        string url    = string.Format("{0}?ErrorUrl={1}", exceptionOperator, server.UrlEncode(s));
                        string script = string.Format("<script language='javascript' type='text/javascript'>window.top.location='{0}';</script>", url);
                        Response.Write(script);
                        Response.End();
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Пример #2
0
        public void ExceptionHandlerStarter()
        {
            string            s      = HttpContext.Current.Request.Url.ToString();
            HttpServerUtility server = HttpContext.Current.Server;

            if (server.GetLastError() != null)
            {
                Exception lastError = server.GetLastError();
                Application["LastError"] = lastError;
                int    statusCode        = HttpContext.Current.Response.StatusCode;
                string exceptionOperator = System.Configuration.ConfigurationManager.AppSettings["ExceptionUrl"];
                try
                {
                    exceptionOperator = new System.Web.UI.Control().ResolveUrl(exceptionOperator);
                    if (!String.IsNullOrEmpty(exceptionOperator) && !s.Contains(exceptionOperator))
                    {
                        string url    = string.Format("{0}?ErrorUrl={1}", exceptionOperator, server.UrlEncode(s));
                        string script = String.Format("<script language='javascript' type='text/javascript'>window.top.location='{0}';</script>", url);
                        Response.Write(script);
                        Response.End();
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Пример #3
0
        /// <summary>
        /// 全局的异常处理
        /// </summary>
        public void ExceptionHandlerStarter()
        {
            SysConfigModel siteConfig = new Apps.BLL.SysConfigBLL().loadConfig(Utils.GetXmlMapPath("Configpath"));

            if (siteConfig.globalexceptionstatus == 1)
            {
                string            s      = HttpContext.Current.Request.Url.ToString();
                HttpServerUtility server = HttpContext.Current.Server;
                if (server.GetLastError() != null)
                {
                    Exception lastError = server.GetLastError();
                    // 此处进行异常记录,可以记录到数据库或文本,也可以使用其他日志记录组件。
                    ExceptionHander.WriteException(lastError);
                    Application["LastError"] = lastError;
                    int    statusCode        = HttpContext.Current.Response.StatusCode;
                    string exceptionOperator = siteConfig.globalexceptionurl;
                    try
                    {
                        if (!String.IsNullOrEmpty(exceptionOperator))
                        {
                            exceptionOperator = new System.Web.UI.Control().ResolveUrl(exceptionOperator);
                            string url    = string.Format("{0}?ErrorUrl={1}", exceptionOperator, server.UrlEncode(s));
                            string script = String.Format("<script language='javascript' type='text/javascript'>window.top.location='{0}';</script>", url);
                            Response.Write(script);
                            Response.End();
                        }
                    }
                    catch { }
                }
            }
        }
Пример #4
0
        private void OnErrorRequest(object s, EventArgs e)
        {
            try
            {
                if (HttpContext.Current == null)
                {
                    return;
                }

                HttpApplication   ap            = s as HttpApplication;
                HttpContext       Context       = HttpContext.Current;
                HttpServerUtility Server        = Context.Server;
                HttpRequest       Request       = Context.Request;
                Exception         lastException = Server.GetLastError();

                if (!(lastException is HttpException))
                {
                    var lex = new Exception("Unhandled Error: ", Server.GetLastError());
                    AppLog.Error(lex);
                }
                else
                {
                    AppLog.Error(lastException);
                }
            }
            catch (Exception exc)
            {
                AppLog.Error(exc);
            }
        }
Пример #5
0
        protected virtual void OnError(object sender, EventArgs args)
        {
            try {
                HttpApplication httpApplication = sender as HttpApplication;
                if (httpApplication == null)
                {
                    return;
                }

                HttpServerUtility server = httpApplication.Server;
                if (server == null)
                {
                    return;
                }

                if (LogifyAlert.Instance.CollectBreadcrumbs)
                {
                    AspBreadcrumbsRecorder.Instance.UpdateBreadcrumb(sender as HttpApplication);
                }

                Exception lastError = server.GetLastError();
                LogifyAlert.Instance.Send(lastError);
            }
            catch { }
        }
Пример #6
0
        public void OnError(Object sender, EventArgs e)
        {
            HttpContext       Context  = HttpContext.Current;
            HttpResponse      Response = Context.Response;
            HttpRequest       Request  = Context.Request;
            HttpServerUtility Server   = Context.Server;

            #region 记录错误日志

            Exception ex  = Server.GetLastError();
            String    msg = String.Format("\r\n\tIP:{0}\r\n\t页面:{1}\r\n\t消息:{2}\r\n\t类型:{3}\r\n\t用户:{4}",
                                          Request.UserHostAddress,
                                          Request.Url.AbsoluteUri,
                                          ex.Message,
                                          ex.GetType(),
                                          Request.UserAgent);
            ILog logger = LogManager.GetLogger("Error");
            logger.Debug(msg);

            #endregion

            Server.ClearError();
            Response.Clear();
            Response.StatusCode             = 410;
            Response.ContentType            = "text/html";
            Response.TrySkipIisCustomErrors = true;
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Context.ApplicationInstance.CompleteRequest();
        }
Пример #7
0
        private void OnUnhandledApplicationException(object sender, EventArgs e)
        {
            StringBuilder message = new StringBuilder("<html><head><style>" +
                                                      "body, table { font-size: 12px; font-family: Arial, sans-serif; }\r\n" +
                                                      "table tr td { padding: 4px; }\r\n" +
                                                      ".header { font-weight: 900; font-size: 14px; color: #fff; background-color: #2b4e74; }\r\n" +
                                                      ".header2 { font-weight: 900; background-color: #c0c0c0; }\r\n" +
                                                      "</style></head><body><table><tr><td class=\"header\">\r\n\r\nUnhandled Exception logged by LogModule.dll:\r\n\r\nappId=");
            string appId = (string)AppDomain.CurrentDomain.GetData(".appId");

            if (appId != null)
            {
                message.Append(appId);
            }
            message.Append("</td></tr>");
            HttpServerUtility server           = HttpContext.Current.Server;
            Exception         currentException = server.GetLastError();

            if (currentException != null)
            {
                message.AppendFormat(
                    "<tr><td class=\"header2\">TYPE</td></tr><tr><td>{0}</td></tr><tr><td class=\"header2\">REQUEST</td></tr><tr><td>{3}</td></tr><tr><td class=\"header2\">MESSAGE</td></tr><tr><td>{1}</td></tr><tr><td class=\"header2\">STACK TRACE</td></tr><tr><td>{2}</td></tr>",
                    currentException.GetType().FullName,
                    currentException.Message,
                    currentException.StackTrace,
                    HttpContext.Current != null ? HttpContext.Current.Request.FilePath : "n/a");
                server.ClearError();
            }
            message.Append("</table></body></html>");
            HttpContext.Current.Response.Write(message.ToString());
            server.ClearError();
        }
Пример #8
0
        public static void HandleLastException(HttpServerUtility httpServerUtility, HttpRequest httpRequest, HttpResponse httpResponse)
        {
            Exception exception = httpServerUtility.GetLastError();

            httpServerUtility.ClearError();

            try
            {
                httpResponse.Clear();
            }
            catch
            {
                LogService.Log(exception, LogType.Fatal);

                return;
            }

            string msg = HandleException(exception, LogType.Fatal).Item1;


            if (httpRequest.IsAjaxRequest())
            {
                var jsonResult = new JsonResultModel(msg, true);

                string response = JsonConvert.SerializeObject(jsonResult);

                httpResponse.Write(response);
            }
            else
            {
                httpResponse.Redirect(string.Format("~/Errors?message={0}", msg));
            }
        }
        public static void Execute(HttpServerUtility server, HttpResponse response)
        {
            Exception exc = server.GetLastError();

            if (exc.GetType() == typeof(HttpException))
            {
                if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
                {
                    return;
                }

                server.Transfer("HttpErrorPage.aspx");
            }
            else if (exc.GetType() == typeof(DinazorAuthorizationException))
            {
                RedirectDinazorResult.RedirectWithData(new DinazorResult()
                {
                    Status  = ResultStatus.Unauthorized,
                    Message = exc.Message
                });
            }

            Log.Error(exc);
            server.ClearError();
        }
Пример #10
0
        public static void Notify(bool allowRedirect, string additionalErrorMessage, Exception lastError)
        {
            HttpRequest       rq  = HttpContext.Current.Request;
            HttpResponse      rsp = HttpContext.Current.Response;
            HttpServerUtility sv  = HttpContext.Current.Server;

            // get error details from system
            if (lastError == null)
            {
                lastError = sv.GetLastError();
            }

            // get full error details containing source snippets and pretty stack trace
            var dump = new Logging.DiagnosticData(lastError);

            dump.AdditionalMessage = additionalErrorMessage;
            sv.ClearError();

            // log the error report by sending to twitch or emailing
            bool wasLogged = LogErrorReport(dump);

            // show nice user friendly screen
            // for developers also show full details on screen - show error on screen for requests from beweb office
            if (dump.HttpStatusCode == 404)
            {
                PageNotFound(Web.LocalUrl, dump);
            }
            else
            {
                DisplayErrorPage(dump.HttpStatusCode, null, dump, wasLogged);
            }
        }
Пример #11
0
 protected void Application_Error(object sender, EventArgs e)
 {
     // ...
     // Use HttpContext.Current to get a Web request processing helper
     HttpServerUtility server    = HttpContext.Current.Server;
     Exception         exception = server.GetLastError();
     // Log an exception
 }
        public static void Application_OnError()
        {
            HttpServerUtility Server = HttpContext.Current.Server;
            Exception         ex     = Server.GetLastError();

            if (ex != null)
            {
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                string        sException = ex.GetType().Name;
                StringBuilder sbMessage  = new StringBuilder();
                sbMessage.Append(ex.Message);
                // 03/10/2006 Paul.  .NET 2.0 returns lowercase type names. Use typeof instead.
                if (ex.GetType() == typeof(FileNotFoundException))
                {
                    // We can get this error for forbidden files such as web.config and global.asa.
                    //return ; // Return would work if 404 entry was made in web.config.
                    //Response.Redirect("~/Home/FileNotFound.aspx?aspxerrorpath=" + Server.UrlEncode(Request.Path));
                    sbMessage = new StringBuilder("File Not Found");
                }
                // 03/10/2006 Paul.  .NET 2.0 returns lowercase type names. Use typeof instead.
                else if (ex.GetType() == typeof(HttpException))
                {
                    HttpException exHttp    = (HttpException)ex;
                    int           nHttpCode = exHttp.GetHttpCode();
                    if (nHttpCode == 403)
                    {
                        //return ; // Return would work if 403 entry was made in web.config.
                        //Response.Redirect("~/Home/AccessDenied.aspx?aspxerrorpath=" + Server.UrlEncode(Request.Path));
                        sbMessage = new StringBuilder("Access Denied");
                    }
                    else if (nHttpCode == 404)
                    {
                        //return ; // Return would work if 404 entry was made in web.config.
                        //Response.Redirect("~/Home/FileNotFound.aspx?aspxerrorpath=" + Server.UrlEncode(Request.Path));
                        sbMessage = new StringBuilder("File Not Found");
                    }
                }
                // 03/10/2006 Paul.  .NET 2.0 returns lowercase type names. Use typeof instead.
                else if (ex.GetType() == typeof(HttpCompileException))
                {
                    HttpCompileException    exCompile = (HttpCompileException)ex;
                    CompilerErrorCollection col       = exCompile.Results.Errors;
                    foreach (CompilerError err in col)
                    {
                        sbMessage.Append("  ");
                        sbMessage.Append(err.ErrorText);
                    }
                }
                SplendidError.SystemError(new StackTrace(true).GetFrame(0), sbMessage.ToString());
                Server.ClearError();
                string sQueryString = String.Format("aspxerrorpath={0}&Exception={1}&Message={2}", Server.UrlEncode(HttpContext.Current.Request.Path), sException, Server.UrlEncode(sbMessage.ToString()));
                HttpContext.Current.Response.Redirect("~/Home/ServerError.aspx?" + sQueryString);
            }
        }
Пример #13
0
        public void OnErrorRequest(object s, EventArgs e)
        {
            try
            {
                if (HttpContext.Current == null)
                {
                    return;
                }

                HttpContext       Context = HttpContext.Current;
                HttpServerUtility Server  = Context.Server;
                HttpRequest       Request = Context.Request;

                //exit if a request for a .net mapping that isn't a content page is made i.e. axd
                if (Request.Url.LocalPath.ToLower().EndsWith(".aspx") == false && Request.Url.LocalPath.ToLower().EndsWith(".asmx") == false &&
                    Request.Url.LocalPath.ToLower().EndsWith(".ashx") == false)
                {
                    return;
                }
                Exception lastException = Server.GetLastError();

                //HttpExceptions are logged elsewhere
                if (!(lastException is HttpException))
                {
                    var lex             = new Exception("Unhandled Error: ", Server.GetLastError());
                    var objExceptionLog = new ExceptionLogController();
                    try
                    {
                        objExceptionLog.AddLog(lex);
                    }
                    catch (Exception ex)
                    {
                        DnnLog.Error(ex);
                    }
                }
            }
            catch (Exception exc)
            {
                //it is possible when terminating the request for the context not to exist
                //in this case we just want to exit since there is nothing else we can do
                DnnLog.Error(exc);
            }
        }
Пример #14
0
 // for testing
 internal static SentryId CaptureLastError(this HttpServerUtility server, IHub hub)
 {
     if (server.GetLastError() is { } exception)
     {
         exception.Data[Mechanism.HandledKey]   = false;
         exception.Data[Mechanism.MechanismKey] = "HttpApplication.Application_Error";
         return(hub.CaptureException(exception));
     }
     return(SentryId.Empty);
 }
Пример #15
0
        public void OnErrorRequest(object s, EventArgs e)
        {
            HttpContext       Context = HttpContext.Current;
            HttpServerUtility Server  = Context.Server;

            Exception lex = new Exception("Unhandled Error: ", Server.GetLastError());
            ExceptionLogController objExceptionLog = new ExceptionLogController();

            objExceptionLog.AddLog(lex);
        }
Пример #16
0
        /// <summary>
        /// Called when error handling is requested.
        /// </summary>
        /// <param name="s">The object with the error</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        public void OnErrorRequest(object s, EventArgs e)
        {
            try
            {
                if (HttpContext.Current == null)
                {
                    return;
                }

                HttpContext       contxt  = HttpContext.Current;
                HttpServerUtility srver   = contxt.Server;
                HttpRequest       request = contxt.Request;

                if (!Initialize.ProcessHttpModule(request, false, false))
                {
                    return;
                }

                Exception lastException = srver.GetLastError();

                //HttpExceptions are logged elsewhere
                if (!(lastException is HttpException))
                {
                    var lex             = new Exception("Unhandled Error: ", srver.GetLastError());
                    var objExceptionLog = new ExceptionLogController();
                    try
                    {
                        objExceptionLog.AddLog(lex);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex);
                    }
                }
            }
            catch (Exception exc)
            {
                //it is possible when terminating the request for the context not to exist
                //in this case we just want to exit since there is nothing else we can do
                Logger.Error(exc);
            }
        }
Пример #17
0
        void Application_Error(object sender, EventArgs e)
        {
            // ...
            // Use HttpContext.Current to get a Web request processing helper
            HttpServerUtility server    = HttpContext.Current.Server;
            Exception         exception = server.GetLastError();

            // Log an exception
            Log.For(this).Error(exception.Message, exception);

            Application[HttpContext.Current.Request.UserHostAddress.ToString()] = exception;
        }
Пример #18
0
    public static void HandleError(this HttpServerUtility server, HttpContext httpContext)
    {
        var currentController = " ";
        var currentAction     = " ";
        var currentRouteData  = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

        if (currentRouteData != null)
        {
            if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
            {
                currentController = currentRouteData.Values["controller"].ToString();
            }
            if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
            {
                currentAction = currentRouteData.Values["action"].ToString();
            }
        }
        var exception = server.GetLastError();

        Logger.ErrorException(exception.Message, exception);

        var controller = DependencyResolver.Current.GetService <ErrorController>();
        var routeData  = new RouteData();
        var action     = "InternalServerError";

        if (exception is HttpException)
        {
            var httpEx = exception as HttpException;
            switch (httpEx.GetHttpCode())
            {
            case 404:
                action = "NotFound";
                break;

            case 401:
                action = "AccessDenied";
                break;
            }
        }
        httpContext.ClearError();
        httpContext.Response.Clear();
        httpContext.Response.StatusCode             = exception is HttpException ? ((HttpException)exception).GetHttpCode() : 500;
        httpContext.Response.TrySkipIisCustomErrors = true;
        routeData.Values["controller"] = "Error";
        routeData.Values["action"]     = action;
        controller.ViewData.Model      = new HandleErrorInfo(exception, currentController, currentAction);
        ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
    }
Пример #19
0
        public static void Execute(HttpServerUtility server, HttpResponse response)
        {
            Exception exc = server.GetLastError();

            if (exc.GetType() == typeof(HttpException))
            {
                if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
                {
                    return;
                }

                server.Transfer("HttpErrorPage.aspx");
            }
            Log.Error(exc);
            server.ClearError();
        }
Пример #20
0
        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            // ...
            // Use HttpContext.Current to get a Web request processing helper
            HttpServerUtility server    = HttpContext.Current.Server;
            Exception         exception = server.GetLastError();

            if (exception is HttpUnhandledException || exception is TargetInvocationException)
            {
                exception = exception.InnerException;
                ASPxWebControl.SetCallbackErrorMessage(exception.Message);
            }

            // Log an exception
            logger.Error(exception);
            // Su dung de hien thi Loi o Trang Error.aspx khi muon hien thi loi o Server Side
            //AddToShowLog(exception.Message, exception.StackTrace);
        }
Пример #21
0
        protected void Application_Error()
        {
            string currentUrl = HttpContext.Current.Request.Url.ToString();

            HttpServerUtility server    = HttpContext.Current.Server;
            Exception         lastError = server.GetLastError();

            if (lastError != null)
            {
                TxtLog.SaveErrorLog("应用程序捕获异常,出错链接:[[[ " + currentUrl + " ]]]", lastError.ToString(), "应用程序异常处理程序");

                RouteData routeData = new RouteData();
                routeData.Values.Add("controller", "base");
                routeData.Values.Add("action", "exception");
                routeData.Values.Add("error", lastError);

                Server.ClearError();
                IController errorController = new Controllers.BaseController();
                errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
            }
        }
Пример #22
0
        void Application_Error(object sender, EventArgs e)
        {
            //// Code that runs when an unhandled error occurs

            //// Get the exception object.
            //Exception exc = Server.GetLastError();

            //// Handle HTTP errors
            //if (exc.GetType() == typeof(HttpException))
            //{
            //    // The Complete Error Handling Example generates
            //    // some errors using URLs with "NoCatch" in them;
            //    // ignore these here to simulate what would happen
            //    // if a global.asax handler were not implemented.
            //    if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
            //        return;

            //    //Redirect HTTP errors to HttpError page
            //    Server.Transfer("HttpErrorPage.aspx");
            //}

            //// For other kinds of errors give the user some information
            //// but stay on the default page
            //Response.Write("<h2>Global Page Error</h2>\n");
            //Response.Write("<p>" + exc.Message + "</p>\n");
            //Response.Write("Return to the <a href='Default.aspx'>Default Page</a>\n");

            //// Log the exception and notify system operators
            //ExceptionUtility.LogException(exc, "DefaultPage");
            //ExceptionUtility.NotifySystemOps(exc);

            //// Clear the error from the server
            //Server.ClearError();

            // Use HttpContext.Current to get a Web request processing helper
            HttpServerUtility server    = HttpContext.Current.Server;
            Exception         exception = server.GetLastError();
        }
 public override Exception GetLastError()
 {
     return(_httpServerUtility.GetLastError());
 }
Пример #24
0
 public override Exception GetLastError()
 {
     return(_server.GetLastError());
 }
        public void Methods_Deny_Unrestricted()
        {
            hsu.ClearError();

            Assert.IsNull(hsu.GetLastError(), "GetLastError");

            Assert.IsNotNull(hsu.HtmlDecode(String.Empty), "HtmlDecode(string)");
            hsu.HtmlDecode(String.Empty, sw);

            Assert.IsNotNull(hsu.HtmlEncode(String.Empty), "HtmlEncode(string)");
            hsu.HtmlEncode(String.Empty, sw);

            try
            {
                Assert.IsNull(hsu.MapPath(String.Empty), "MapPath(string)");
            }
            catch (NullReferenceException)
            {
                // ms 1.x
            }

            try
            {
                hsu.Transfer("/");
            }
            catch (NullReferenceException)
            {
                // ms
            }
            try
            {
                hsu.Transfer("/", true);
            }
            catch (NullReferenceException)
            {
                // ms
            }
            try
            {
                hsu.Transfer("/", false);
            }
            catch (NullReferenceException)
            {
                // ms
            }
#if NET_2_0
            try
            {
                hsu.Transfer((IHttpHandler)null, true);
            }
            catch (NullReferenceException)
            {
                // ms
            }
            try
            {
                hsu.Transfer((IHttpHandler)null, false);
            }
            catch (NullReferenceException)
            {
                // ms
            }
#endif
            try
            {
                Assert.IsNotNull(hsu.UrlDecode(url), "UrlDecode(string)");
            }
            catch (NullReferenceException)
            {
                // ms
            }
            try
            {
                hsu.UrlDecode("http://www.mono-project.com/", sw);
            }
            catch (NullReferenceException)
            {
                // ms
            }

            Assert.IsNotNull(hsu.UrlEncode(String.Empty), "UrlEncode(string)");
            hsu.UrlEncode(String.Empty, sw);

            Assert.IsNotNull(hsu.UrlPathEncode(String.Empty), "UrlPathEncode(string)");
        }
Пример #26
0
        private void Application_Error(object sender, EventArgs e)
        {
            //https://msdn.microsoft.com/en-us/library/24395wz3.aspx

            HttpServerUtility server             = HttpContext.Current.Server;
            Exception         exception          = server.GetLastError();
            string            currentPageRequest = HttpContext.Current.Request.FilePath;


            if (Configuration.Development.GetIsEnabledDebugDeveloperModeShowGlobalPageError())
            {
                if (exception.GetType() == typeof(HttpException))
                {
                    Server.Transfer("~/ErrorPageHttp.aspx");
                }
                else
                {
                    Response.Write("<h2>Global Page Error</h2>\n");
                    Response.Write(
                        "<p>" + exception.Message + "</p>\n");
                    Response.Write("Return to the <a href='/Default.aspx'>" +
                                   "Default Page</a>\n");

                    if (Context.Request.IsLocal)
                    {
                        Response.Write("<p>" + exception.Source + "</p>\n");
                        Response.Write("<p>" + exception.InnerException + "</p>\n");
                        Response.Write("<p>" + exception.StackTrace + "</p>\n");
                    }
                }

                if (!_previousPageError.Equals(currentPageRequest))
                {
                    ExceptionUtility.LogException(exception, currentPageRequest);
                    ExceptionUtility.NotifySystemOps(exception);
                }
            }

            // if not in DEV MODE, write error to .txt
            if (!Configuration.Development.GetIsEnabledDeveloperMode())
            {
                // devexpress callback error
                // Use HttpContext.Current to get a Web request processing helper

                // is http?
                if (exception is HttpUnhandledException)
                {
                    HttpException ex = (HttpException)Server.GetLastError();
                    //Exception innerexception = exception.InnerException;

                    // Log an exception
                    // TODO, send email to admin.
                    if (!_previousPageError.Equals(currentPageRequest))
                    {
                        ExceptionUtility.LogException(exception, currentPageRequest);
                        ExceptionUtility.NotifySystemOps(exception);


                        // log to logger
                        if (HttpContext.Current != null && HttpContext.Current.Request != null)
                        {
                            Global.LogError(Context, Global.EnumLogCategories.GENERAL,
                                            "HTTP " + ex.GetHttpCode() + ": " + Request.RawUrl.ToString(),
                                            ex);
                        }
                    }

                    // options to show info to user:
                    // 1. show a blank page:
                    //Server.ClearError();
                    // 2. redirect to a page
                    // Response.Redirect("~/Errors/ErrorPageHttp.aspx");
                    // 3. do nothing, go to customErrors configuration in web.config and/or show asp.net error
                }
                else
                {
                    // other NO http errors
                    ExceptionUtility.LogException(exception, currentPageRequest);
                    ExceptionUtility.NotifySystemOps(exception);

                    // log to logger
                    if (HttpContext.Current != null && HttpContext.Current.Request != null)
                    {
                        Global.LogError(Context, Global.EnumLogCategories.GENERAL,
                                        "Error " + exception.HResult + ": " + Request.RawUrl.ToString(),
                                        exception);
                    }
                }
            }
            else
            {
                ExceptionUtility.LogException(exception, currentPageRequest);
                ExceptionUtility.NotifySystemOps(exception);

                // log to logger, no works in callback mode

                /*
                 * if (HttpContext.Current != null && HttpContext.Current.Request != null)
                 *  Global.LogError( Context, Global.EnumLogCategories.GENERAL,
                 *      "Error " + exception.HResult + ": " + Request.RawUrl.ToString(),
                 *      exception );
                 */

                ExceptionUtility.LogException(exception, currentPageRequest);
                ExceptionUtility.NotifySystemOps(exception);
            }



            //_previousException = exception;
            _previousPageError = currentPageRequest;
        }
        //private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        public static void HandleError <T>(this HttpServerUtility server, HttpContext httpContext) where T : Controller
        {
            var currentController = " ";
            var currentAction     = " ";
            var currentRouteData  = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

            if (currentRouteData != null)
            {
                if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
                {
                    currentController = currentRouteData.Values["controller"].ToString();
                }

                if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
                {
                    currentAction = currentRouteData.Values["action"].ToString();
                }
            }

            var exception     = server.GetLastError();
            var httpException = exception as HttpException;

            if (httpException == null)
            {
                var verb = httpContext.Request.HttpMethod;

                var exceptionMessage = string.Format("Error while executing action {0}/{1} of controller {2} ({3}): {4}",
                                                     currentAction, verb, currentController, httpContext.Request.Url, exception.Message);

                //Logger.Error(exception, exceptionMessage);
            }

            var controller = DependencyResolver.Current.GetService <T>();
            var routeData  = new RouteData();
            var action     = "InternalServerError";

            if (httpException != null)
            {
                switch (httpException.GetHttpCode())
                {
                case 404:
                    action = "NotFound";
                    break;

                case 401:
                    action = "AccessDenied";
                    break;
                }
            }

            httpContext.ClearError();
            httpContext.Response.Clear();
            httpContext.Response.StatusCode = httpException != null?httpException.GetHttpCode() : 500;

            httpContext.Response.TrySkipIisCustomErrors = true;

            routeData.Values["controller"] = "Error";
            routeData.Values["action"]     = action;

            controller.ViewData.Model = new HandleErrorInfo(exception, currentController, currentAction);
            ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
        }
Пример #28
0
        public static void ReportWebException(HttpServerUtility Server, AuditEventType eventType)
        {
            bool   ignoreException = false;
            string body            = "An error has occurred while a user was browsing OCM:<br><br>";

            object exceptionObject = null;

            if (Server.GetLastError() != null)
            {
                Exception exp = Server.GetLastError();
                exceptionObject = exp;

                if (exp.InnerException != null)
                {
                    exceptionObject = exp.InnerException;
                }

                body += ((Exception)exceptionObject).ToString();

                HttpContext con = HttpContext.Current;
                if (con.Request.Url != null)
                {
                    body += "<br><br>Request Url:" + con.Request.Url.ToString();

                    //special case to avoid reporting /trackback url exceptions
                    if (con.Request.Url.ToString().EndsWith("/trackback/"))
                    {
                        ignoreException = true;
                    }
                }
                if (con.Request.UserAgent != null)
                {
                    body += "<br>User Agent: " + con.Request.UserAgent;
                }
                body += "<br><br>" + DateTime.UtcNow.ToString();
            }

            if (exceptionObject is System.Web.HttpRequestValidationException || exceptionObject is System.Web.UI.ViewStateException)
            {
                ignoreException = true;
            }

            if (!ignoreException)
            {
                if (ConfigurationManager.AppSettings["EnableErrorNotifications"] == "true")
                {
                    NotificationManager notification = new NotificationManager();

                    var msgParams = new Hashtable()
                    {
                        { "Description", "System Error" },
                        { "Name", "OCM Website" },
                        { "Email", "*****@*****.**" },
                        { "Comment", body }
                    };

                    notification.PrepareNotification(NotificationType.ContactUsMessage, msgParams);
                    notification.SendNotification(NotificationType.ContactUsMessage);
                }

                AuditLogManager.Log(null, eventType, body, null);
            }
        }
Пример #29
0
        /// <summary>
        /// 在 HttpApplication 或其派生类的 Application_Error 中调用此方法以生成静态页
        /// </summary>
        /// <param name="httpApplication"></param>
        /// <param name="htmlFileDirectoryName">用于存放生成的html文件的文件夹</param>
        /// <param name="cycleMode"></param>
        public static void Staticize(this HttpApplication httpApplication, string htmlFileDirectoryName = "html", string cycleMode = "DD")
        {
            HttpContext       context  = httpApplication.Context;
            HttpServerUtility server   = httpApplication.Server;
            HttpRequest       request  = httpApplication.Request;
            HttpResponse      response = httpApplication.Response;

            if (!"GET".Equals(request.HttpMethod.ToUpper()))//非GET请求则退出
            {
                return;
            }
            if (YuYuMvcStaticizeConfigurationManager.StaticizeRoutes.Count == 0)//没有配置静态化路由则退出
            {
                return;
            }
            HttpException httpException = server.GetLastError() as HttpException;

            if (httpException == null)//异常为空则退出
            {
                return;
            }
            if (httpException.GetHttpCode() != 404)//非404错误则退出
            {
                return;
            }
            string url            = request.Url.ToString(),
                   pathAndQuery   = request.Url.PathAndQuery,
                   path           = request.Path,
                   dateFolderName = DateTime.Now.GetDirectoryName();
            UrlHelper urlHelper   = new UrlHelper(request.RequestContext, RouteTable.Routes);

            context.RewritePath(pathAndQuery.Replace("/" + htmlFileDirectoryName + "/" + dateFolderName, string.Empty));
            RouteData data = YuYuMvcStaticizeConfigurationManager.StaticizeRoutes.GetRouteData(new HttpContextWrapper(context));

            if (data == null)//路由数据为空则退出
            {
                return;
            }
            string actionName = data.Values["action"] as string, controllerName = data.Values["controller"] as string;

            if (string.IsNullOrWhiteSpace(actionName) || string.IsNullOrWhiteSpace(controllerName))//处理映射程序不存在则退出
            {
                return;
            }
            string urlstring     = urlHelper.Action(actionName, controllerName, data.Values), //映射到程序的Url
                   filePath      = server.MapPath("~" + path),                                //请求的文件路径
                   content       = string.Empty;
            string directoryPath = filePath.Remove(filePath.LastIndexOf("\\"));

            if (!Directory.Exists(directoryPath))
            {
                string htmlFolderPath = server.MapPath("~/" + htmlFileDirectoryName + "/");
                try
                {
                    if (Directory.Exists(htmlFolderPath))
                    {
                        string[] directories = Directory.GetDirectories(htmlFolderPath);
                        new Thread(() =>
                        {
                            if (directories == null || directories.Length == 0)
                            {
                                return;
                            }
                            for (int i = 0; i < directories.Length; i++)
                            {
                                Directory.Delete(directories[i], true);
                            }
                        }).Start();
                    }
                    Directory.CreateDirectory(directoryPath);
                }
                catch { }
            }
            if (Directory.Exists(directoryPath))
            {
                try
                {
                    using (Stream responseSteam = WebRequest.Create(url.Replace(pathAndQuery, string.Empty) + urlstring).GetResponse().GetResponseStream())
                    {
                        StreamReader sr = new StreamReader(responseSteam);
                        content = sr.ReadToEnd();
                        sr.Close();
                        sr.Dispose();
                        responseSteam.Close();
                    }
                    if (content == null || content.Length == 0)
                    {
                        return;
                    }
                    using (FileStream fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        StreamWriter sw = new StreamWriter(fileStream);
                        sw.Write(content);
                        sw.Close();
                        sw.Dispose();
                        fileStream.Close();
                        fileStream.Dispose();
                    }
                }
                catch (Exception)
                {
                    return;
                }
            }
            if (File.Exists(filePath))
            {
                response.Redirect(request.Url.ToString());
            }
        }
Пример #30
0
        public static void Configure(HttpContext httpContext, HttpServerUtility server)
        {
            var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
            var requestContext   = ((MvcHandler)httpContext.CurrentHandler).RequestContext;
            var ex = server.GetLastError();

            #region Current Route
            var location = GetCurrentRoute(httpContext);
            #endregion

            #region Log
            var _logger = DependencyResolver.Current.GetService <ILogger>();
            #endregion

            #region HttpException
            int  httpStatusCode = HttpStatusCode.InternalServerError.ToInt();
            Guid correlationId  = Guid.Empty;

            if (ex is HttpException)
            {
                var httpException = ex as HttpException;
                httpStatusCode = httpException.GetHttpCode();
                correlationId  = _logger.Warning(ex, location);
            }
            else
            {
                correlationId = _logger.Fatal(ex, location);
            }
            #endregion

            #region Clear HttpContext
            httpContext.ClearError();
            httpContext.Response.Clear();
            #endregion

            #region Controller Factory
            ControllerContext controllerContext = new ControllerContext();
            CreateControllerContext(requestContext, httpContext, ref controllerContext);
            #endregion

            if (requestContext.HttpContext.Request.IsAjaxRequest())
            {
                var jsonResult = new JsonResult
                {
                    Data = new Result(ex is HttpException ? ex.Message : Definition.Message.Error, "", correlationId,
                                      (HttpStatusCode)httpStatusCode).Json(),

                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };

                jsonResult.ExecuteResult(controllerContext);
            }
            else
            {
                var message = Definition.Message.Get(httpStatusCode);

                var viewResult = new ViewResult
                {
                    ViewName = "~/Views/Shared/_Error.cshtml",

                    ViewData = new ViewDataDictionary(new ErrorInfo(ex, correlationId, message, httpStatusCode, GetCurrentController(currentRouteData), GetCurrentAction(currentRouteData)))
                };

                viewResult.ExecuteResult(controllerContext);
            }

            httpContext.Response.End();
        }