MvcApplication

 

 

 

 

  // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
           
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  //它的主要作用是将全局过滤器进行注册,而全局过滤器可以在RegisterGlobalFilters这个方法里进行设置
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            
            //List<AllSessions> listAllSessions = new List<AllSessions>();
            //Application["listAllSessions"] = listAllSessions;
        }
        void Application_End(object sender, EventArgs e)
        {
            //不是每次请求都调用
            //在应用程序关闭时运行的代码,在最后一个HttpApplication销毁之后执行
            //比如IIS重启,文件更新,进程回收导致应用程序转换到另一个应用程序域
        }

        void Session_Start(object sender, EventArgs e)
        {  
            //不是每次请求都调用
            //会话开始时执行           
                //System.Text.StringBuilder sb = new System.Text.StringBuilder();
                //foreach (string item in Session.Contents)
                //{
                //    sb.Append("Session变量:" + item.ToString() + "值:" + Session[item]);
                //}
                //Application.Lock();
                //List<AllSessions> listAllSessions = (List<AllSessions>)Application["listAllSessions"];
                //string SessionID = Session.SessionID;
                //if (listAllSessions.Where(x=>x.SessionID.Contains(SessionID)).Count()==0)
                //{
                //    AllSessions allSessions = new AllSessions();
                //    allSessions.SessionID = SessionID;
                //    listAllSessions.Add(allSessions);
                //    Application["listAllSessions"] = listAllSessions;
                //}
                //Application.UnLock();
         
        }

        void Session_End(object sender, EventArgs e)
        {
            //不是每次请求都调用
            //会话结束或过期时执行
            //不管在代码中显式的清空Session或者Session超时自动过期,此方法都将被调用
            //System.Text.StringBuilder sb = new System.Text.StringBuilder();    foreach (string item in Session.Contents)
            //{
            //    sb.Append("Session变量:" + item.ToString() + "值:" + Session[item]);
            //}
            //string sessionID = Session.SessionID;
            //List<AllSessions> listAllSessins = (List<AllSessions>)Application["listAllSessions"];
            //Application.Lock();
            //AllSessions allSession = listAllSessins.FirstOrDefault(x => x.SessionID == sessionID);
            //listAllSessins.Remove(allSession);
            //Application.UnLock();
            //string sMsg = string.Empty;
            //sMsg = "--------------Session_End---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ms") + "----Start----------------------------------";
            //sMsg += "\r\n当前用户数量:" + listAllSessins.Count;
            //foreach (var item in listAllSessins)
            //{
            //    sMsg += "\r\nSessionID:" + item.SessionID;
            //    if (item.account != null)
            //    {
            //        sMsg += "\r\n用户姓名:" + item.account.Name;
            //    }
            //}
            //sMsg += "\r\n------------Session_End---------END----------------------------------\r\n";
            //WriteLogs("Session记录", sMsg);
        }

        void Application_Init(object sender, EventArgs e)
        {
            //不是每次请求都调用
            //在每一个HttpApplication实例初始化的时候执行
        }

        void Application_Disposed(object sender, EventArgs e)
        {
            //不是每次请求都调用
            //在应用程序被关闭一段时间之后,在.net垃圾回收器准备回收它占用的内存的时候被调用。
            //在每一个HttpApplication实例被销毁之前执行
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            ExceptionHandlerStarter();
            //不是每次请求都调用
            //所有没有处理的错误都会导致这个方法的执行
        }
        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)
                        && !lastError.Message.Contains("/Images/noPic.gif"))
                    {     
                        #region 写日志                    
                      
                        NameValueCollection gets = HttpContext.Current.Request.QueryString;
                        List<string> listGets = new List<string>();
                        foreach (string item in gets)
                        {
                            listGets.Add(string.Format("{0}={1}", item, gets[item]));
                        }
                        NameValueCollection posts = HttpContext.Current.Request.Form;
                        List<string> listPosts = new List<string>();
                        foreach (string item in posts)
                        {
                            listPosts.Add(string.Format("{0}={1}",item,posts[item]));
                        }
                        System.Text.StringBuilder sbError = new System.Text.StringBuilder();
                        sbError.Append("-----------------------Application_Error------Start--------------------------------------");
                        sbError.Append("\r\n 出错时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        sbError.Append("\r\n 错误信息:" + lastError.Message);
                        sbError.Append("\r\n Get请求参数:" + string.Join("&", listGets.ToArray()));
                        sbError.Append("\r\n Post请求参数:" + string.Join("&", listPosts.ToArray()));
                        //  sw.WriteLine("\r\n Controller:" + lastError.GetType().FullName);
                        // sw.WriteLine("\r\n 方法:" + filterContext.RouteData.GetRequiredString("action"));                           
                        sbError.Append("\r\n 堆栈信息:" + lastError.StackTrace);
                        sbError.Append("\r\n----------------------Application_Error-------End-------------------------------------------\r\n");
                        WriteLogs("Error", sbError.ToString());   
                    
                        #endregion

                        Server.ClearError();//在Global.asax中调用Server.ClearError方法相当于是告诉Asp.Net系统抛出的异常已经被处理过了,不需要系统跳转到Asp.Net的错误黄页了。如果想在Global.asax外调用ClearError方法可以使用HttpContext.Current.ApplicationInstance.Server.ClearError()。
                        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)
                {
                }

            }
        }

        /*********************************************************************/
        //每次请求都会按照顺序执行以下事件
        /*********************************************************************/

        void Application_BeginRequest(object sender, EventArgs e)
        {
            //每次请求时第一个出发的事件,这个方法第一个执行
          
        }

        void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            //在执行验证前发生,这是创建验证逻辑的起点
        }

        void Application_AuthorizeRequest(object sender, EventArgs e)
        {
            //当安全模块已经验证了当前用户的授权时执行
        }

        void Application_ResolveRequestCache(object sender, EventArgs e)
        {
            //当ASP.NET完成授权事件以使缓存模块从缓存中为请求提供服务时发生,从而跳过处理程序(页面或者是WebService)的执行。
            //这样做可以改善网站的性能,这个事件还可以用来判断正文是不是从Cache中得到的。
        }

        //------------------------------------------------------------------------
        //在这个时候,请求将被转交给合适程序。例如:web窗体将被编译并完成实例化
        //------------------------------------------------------------------------

        void Application_AcquireRequestState(object sender, EventArgs e)
        {
            //读取了Session所需的特定信息并且在把这些信息填充到Session之前执行
        //    HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
            //foreach (DictionaryEntry item in Session)
            //{
            //    object key = item.Key;  //获取键
            //    object value = item.Value;  //获取值
            //}

        }

        void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            //在合适的处理程序执行请求前调用
            //这个时候,Session就可以用了
            string Url = Request.Url.ToString();
            #region
            //if (!Url.Contains(".js") && !Url.Contains(".css") && !Url.Contains(".ico") && !Url.Contains(".jpg") && !Url.Contains(".png") && !Url.Contains(".jpg"))
            //{
            //    List<AllSessions> listAllSessins = (List<AllSessions>)Application["listAllSessions"];               
            //    if (listAllSessins.FirstOrDefault(x => x.SessionID == Session.SessionID) == null)
            //    {
            //        AllSessions allSession = new AllSessions();
            //        allSession.SessionID = Session.SessionID;                 
            //        Application.Lock();
            //        listAllSessins.Add(allSession);
            //        Application["listAllSessions"] = listAllSessins;
            //        Application.UnLock();
            //    }               
            //    string sMsg = string.Empty;
            //    sMsg = "-----------Application_PreRequestHandlerExecute---" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ms") + "-------Start----------------------------------";
            //    sMsg += "\r\n当前用户数量:" + listAllSessins.Count;
            //    sMsg += "\r\n访问页面:" + Url;
            //    sMsg += "\r\nRequest.AcceptTypes:" + string.Join("&&&", Request.AcceptTypes);
            //    sMsg += "\r\nRequest.AnonymousID:" + Request.AnonymousID;
            //    sMsg += "\r\nRequest.ApplicationPath;" + Request.ApplicationPath;
            //    sMsg += "\r\nRequest.AppRelativeCurrentExecutionFilePath;" + Request.AppRelativeCurrentExecutionFilePath;
            //    sMsg += "\r\nRequest.Browser;" + Request.Browser;
            //    sMsg += "\r\nRequest.ClientCertificate;" + Request.ClientCertificate;
            //    sMsg += "\r\nRequest.ContentEncoding;" + Request.ContentEncoding;
            //    sMsg += "\r\nRequest.ContentLength;" + Request.ContentLength;
            //    sMsg += "\r\nRequest.ContentType;" + Request.ContentType;
            //    sMsg += "\r\nRequest.Cookies.AllKeys;" + string.Join("$$$", Request.Cookies.AllKeys);
            //    sMsg += "\r\nRequest.CurrentExecutionFilePath;" + Request.CurrentExecutionFilePath;
            //    sMsg += "\r\nRequest.CurrentExecutionFilePathExtension;" + Request.CurrentExecutionFilePathExtension;
            //    sMsg += "\r\nRequest.FilePath;" + Request.FilePath;
            //    sMsg += "\r\nRequest.Files.AllKeys;" + string.Join("&&&", Request.Files.AllKeys);
            //    sMsg += "\r\nRequest.Form.AllKeys;" + string.Join("&&&", Request.Form.AllKeys);
            //    sMsg += "\r\nRequest.HttpMethod;" + Request.HttpMethod;
            //    sMsg += "\r\nRequest.IsAuthenticated;" + Request.IsAuthenticated;
            //    sMsg += "\r\nRequest.IsLocal;" + Request.IsLocal;
            //    sMsg += "\r\nRequest.IsSecureConnection;" + Request.IsSecureConnection;
            //    sMsg += "\r\nRequest.Params.AllKeys;" + string.Join("&&&", Request.Params.AllKeys);
            //    sMsg += "\r\nRequest.Path;" + Request.Path;
            //    sMsg += "\r\nRequest.PathInfo;" + Request.PathInfo;
            //    sMsg += "\r\nRequest.PhysicalApplicationPath;" + Request.PhysicalApplicationPath;
            //    sMsg += "\r\nRequest.PhysicalPath;" + Request.PhysicalPath;
            //    sMsg += "\r\nRequest.QueryString.AllKeys;" + string.Join("&&&", Request.QueryString.AllKeys);
            //    sMsg += "\r\nRequest.RawUrl;" + Request.RawUrl;
            //    sMsg += "\r\nRequest.RequestType;" + Request.RequestType;
            //    sMsg += "\r\nRequest.ServerVariables.AllKeys;" + string.Join("&&&", Request.ServerVariables.AllKeys);
            //    sMsg += "\r\nRequest.TotalBytes;" + Request.TotalBytes;
            //    sMsg += "\r\nRequest.UrlReferrer;" + Request.UrlReferrer;
            //    sMsg += "\r\nRequest.UserAgent;" + Request.UserAgent;
            //    sMsg += "\r\nRequest.UserHostAddress;" + Request.UserHostAddress;
            //    sMsg += "\r\nRequest.UserHostName;" + Request.UserHostName;
            //    sMsg += "\r\nRequest.UserLanguages;" + Request.UserLanguages;

            //    foreach (var item in listAllSessins)
            //    {
            //        sMsg += "\r\nSessionID:" + item.SessionID;
            //        if (item.account == null && item.SessionID == Session.SessionID && Session["account"] != null)
            //        {
            //            item.account = (QiDian.Uitility.Account)Session["account"];
            //        }
            //        if (item.account != null)
            //        {
            //            sMsg += "\r\n用户姓名:" + item.account.Name;
            //        }
            //    }
            //    sMsg += "\r\n--------Application_PreRequestHandlerExecute-------------END----------------------------------\r\n";
            //     WriteLogs("Session记录", sMsg);
            //}
            #endregion
        }

        //-------------------------------------------------
        //在这个时候,页面代码将会被执行,页面呈现为HTML
        //-------------------------------------------------

        void Application_PostRequestHandlerExecute(object sender, EventArgs e)
        {
            //当处理程序完成对请求的处理后被调用。
        }

        void Application_ReleaseRequestState(object sender, EventArgs e)
        {
            //释放请求状态
        }

        void Application_UpdateRequestCache(object sender, EventArgs e)
        {
            //为了后续的请求,更新响应缓存时被调用
        }

        void Application_EndRequest(object sender, EventArgs e)
        {
            //EndRequest是在响应Request时最后一个触发的事件
            //但在对象被释放或者从新建立以前,适合在这个时候清理代码
        }

        void Application_PreSendRequestHeaders(object sender, EventArgs e)
        {
            //向客户端发送Http标头之前被调用
        }

        void Application_PreSendRequestContent(object sender, EventArgs e)
        {
            //向客户端发送Http正文之前被调用
        }
        void WriteLogs(string fileName,string sMsg)
        {
            string FilePath = HttpContext.Current.Server.MapPath("/errorLog/" + DateTime.Now.ToString("yyyyMM"));
            if (!System.IO.Directory.Exists(FilePath))
            {
                System.IO.Directory.CreateDirectory(FilePath);
            }
            string filePath = string.Format("{0}/{1}.txt", FilePath, DateTime.Now.ToString("yyyyMMdd") + fileName);
            using (System.IO.StreamWriter sw=new System.IO.StreamWriter(filePath,true,System.Text.Encoding.UTF8))
            {
                sw.WriteLine(sMsg);
            }
        }
    }

    public class AllSessions
    {
        public string SessionID { get; set; }
        public NameObjectCollectionBase.KeysCollection Keys { get; set; }
      public  QiDian.Uitility.Account account { get; set; }
    }

 

  

posted on 2019-09-03 21:50  欢笑一声  阅读(185)  评论(0)    收藏  举报

导航