Asp.Net网站统一处理错误信息

1.创建Global.asax文件

2.在Application_Error里统一处理,可以写入文件,也可以写入SQL。代码如下

            Exception ex = Server.GetLastError().GetBaseException();

            StringBuilder sb = new StringBuilder();

            sb.AppendLine(DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));



            //有被注入风险

            string ip = "";



            if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)

            {

                ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();

            }

            else

            {

                ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();

            }



            sb.AppendLine("IP地址:" + ip);

            sb.AppendLine("浏览器:" + Request.Browser.Browser.ToString());

            sb.AppendLine("浏览器版本:" + Request.Browser.MajorVersion.ToString());

            sb.AppendLine("操作系统:" + Request.Browser.Platform.ToString());

            sb.AppendLine("错误信息:");

            sb.AppendLine("请求地址:" + Request.Url.ToString());

            sb.AppendLine("错误信息:" + ex.Message);

            sb.AppendLine("错误源:" + ex.Source);

            sb.AppendLine("异常方法:" + ex.TargetSite);

            sb.AppendLine("堆栈信息:" + ex.StackTrace);

            sb.AppendLine("====================================================================================================================");

 

            string logFilePath = Server.MapPath("~/log/");



            if (!Directory.Exists(logFilePath))

            {

                Directory.CreateDirectory(logFilePath);

            }



            File.AppendAllText(logFilePath + DateTime.Now.ToString("yyyy.MM.dd") + ".log", sb.ToString(), Encoding.UTF8);



            Server.ClearError();

            Response.Redirect("myError.htm");
View Code

对于注入问题可看

http://www.cnblogs.com/kingthy/archive/2007/11/24/970783.html

http://www.cnblogs.com/chengmo/archive/2013/05/29/php.html

 

你可能感兴趣的:(asp.net)