zoukankan      html  css  js  c++  java
  • 动态注册HttpModule管道,实现global.asax功能

    1.所用类库有 Microsoft.Web.Infrastructure.dll 和WebActivator.dll

    2.类代码如下

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web;
    using Microsoft.Web.Infrastructure.DynamicModuleHelper;
    using WebActivator;
    /// <summary>
    ///Test 的摘要说明
    /// </summary>
    /// 
    [assembly: WebActivator.PreApplicationStartMethod(typeof(RegisteModule.PreApplicationStartCode), "PreStart")]
    namespace RegisteModule
    {
        public class CustomModule : IHttpModule
        {
            public void Init(HttpApplication context)
            {
                context.BeginRequest += new EventHandler(context_BeginRequest);
                context.Error += new EventHandler(application_Error);
               
            }
    
            void context_BeginRequest(object sender, EventArgs e)
            {
                HttpApplication ap = sender as HttpApplication;
                if (ap != null)
                {
                    string msg = " context_BeginRequest=="+DateTime.Now+"
    
    ";
                    System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("~/log.txt"),msg);
                    ap.Response.Write("测试PreApplicationStartMethod<br/>");
    
                }
    
            }
    
            void context_ErrorRequest(object sender, EventArgs e)
            {
                HttpApplication ha = sender as HttpApplication;
                var error = ha.Server.GetLastError();
                var code = (error is HttpException) ? (error as HttpException).GetHttpCode() : 500;
                if (code != 404)
                {
                }
    
                //记录到日志文件
    
                System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("~/log.txt"), error.InnerException.ToString()+"
    
    ");
    
                ha.Server.ClearError();
                ha.Response.Write(error.Message);
                ha.Response.End();
            }
    
            void application_Error(object sender, EventArgs e)
            {
    
                HttpApplication ha = sender as HttpApplication;
                var Server = ha.Server;
                var Request = ha.Request;
                // 在出现未处理的错误时运行的代码
                Exception ex = Server.GetLastError().GetBaseException();
                StringBuilder str = new StringBuilder();
                str.Append("
    " + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
                str.Append("
    .客户信息:");
    
    
                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();
                }
                str.Append("
    	Ip:" + ip);
                str.Append("
    	浏览器:" + Request.Browser.Browser.ToString());
                str.Append("
    	浏览器版本:" + Request.Browser.MajorVersion.ToString());
                str.Append("
    	操作系统:" + Request.Browser.Platform.ToString());
                str.Append("
    .错误信息:");
                str.Append("
    	页面:" + Request.Url.ToString());
                str.Append("
    	错误信息:" + ex.Message);
                str.Append("
    	错误源:" + ex.Source);
                str.Append("
    	异常方法:" + ex.TargetSite);
                str.Append("
    	堆栈信息:" + ex.StackTrace);
                str.Append("
    --------------------------------------------------------------------------------------------------");
                //创建路径
                string upLoadPath = Server.MapPath("~/log/");
                if (!System.IO.Directory.Exists(upLoadPath))
                {
                    System.IO.Directory.CreateDirectory(upLoadPath);
                }
                //创建文件 写入错误
                System.IO.File.AppendAllText(upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + ".log", str.ToString(), System.Text.Encoding.UTF8);
                //处理完及时清理异常
                Server.ClearError();
            }
    
            public void Dispose()
            {
                //nothing to do here
            }
        }
    
    
    
        public class PreApplicationStartCode
        {
            private static bool hasLoaded;
    
            public static void PreStart()
            {
                if (!hasLoaded)
                {
                    hasLoaded = true;
                    //注意这里的动态注册,此静态方法在Microsoft.Web.Infrastructure.DynamicModuleHelper
                    DynamicModuleUtility.RegisterModule(typeof(CustomModule));
                }
            }
        }
    }
    View Code

    3.测试代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
            throw new Exception("this is error");
        }
    }
    View Code

    参考内容 http://www.cnblogs.com/TomXu/p/3756846.html

  • 相关阅读:
    四种访问修饰符详解(推荐)
    三层架构中DAL层Sqlhelper怎样快速掌握?(常用)
    ASP.NET中最常用的验证控件使用方法(推荐)
    .NetFrom验证方便的webconfig 配置及前台使用(推荐)
    CefSharp访问需要认证网页或接口(在Request的Headers中添加认证Token)
    CentOS7中配置vsftpd
    CentOS7下安装RabbitMQ
    CentOS7下让Asp.Net Core的网站自动运行
    Winform下的Combox根据值来选中项
    golang简单实现jwt验证(beego、xorm、jwt)
  • 原文地址:https://www.cnblogs.com/tiancai/p/6489565.html
Copyright © 2011-2022 走看看