动态注册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+"\n\r";
                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()+"\n\r");

            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("\r\n" + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
            str.Append("\r\n.客户信息:");


            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("\r\n\tIp:" + ip);
            str.Append("\r\n\t浏览器:" + Request.Browser.Browser.ToString());
            str.Append("\r\n\t浏览器版本:" + Request.Browser.MajorVersion.ToString());
            str.Append("\r\n\t操作系统:" + Request.Browser.Platform.ToString());
            str.Append("\r\n.错误信息:");
            str.Append("\r\n\t页面:" + Request.Url.ToString());
            str.Append("\r\n\t错误信息:" + ex.Message);
            str.Append("\r\n\t错误源:" + ex.Source);
            str.Append("\r\n\t异常方法:" + ex.TargetSite);
            str.Append("\r\n\t堆栈信息:" + ex.StackTrace);
            str.Append("\r\n--------------------------------------------------------------------------------------------------");
            //创建路径
            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

posted @ 2017-03-02 11:14  甜菜波波  阅读(318)  评论(0编辑  收藏  举报