动态注册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

转载于:https://www.cnblogs.com/tiancai/p/6489565.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值