zoukankan      html  css  js  c++  java
  • (原创)利用HttpModule非侵入式的显示异常信息

    在工作中,我们常常会需要维护一些老的asp.net程序,这些程序通常没有完善的异常处理机制,在生产环境中,web.config中的customErrors节点的mode属性通常被设为On,这样,当程序在生产环境中出错之后,asp.net只是默认显示一个界面,告诉你程序出错了,但异常信息什么的通通没有,这时,要调试异常,就非要把代码拿到本地,用调试模式或为相应的代码加上异常处理,这样做起来显得很麻烦。在这里我介绍以一个简单的方法,不需要拿到代码,仅需要为web.config添加一个配置项,并向asp.net程序bin目录下copy一个dll就可以方便的显示异常信息。

    我们可以利用 HttpModule 统一干预、处理(例如: 过滤关键字) ASP.Net WebForm Control 的输出,就利用它,我们来为程序构建一个统一的简单异常处理模块。

    首先,新建一个项目,起名为ErrorProcessHttpModule,新建一个类,实现IhttpModule接口,代码如下

    public class ErrorProcessHttpModule : IHttpModule

        {

            private void Application_ErrorHandle(object sender, EventArgs e)

            {

                string msg = HttpContext.Current.Server.GetLastError().ToString();

                HttpContext.Current.Response.Write(msg);

            }

     

            #region IHttpModule Members

            public void Dispose()

            {

               

            }

     

            public void Init(HttpApplication context)

            {

                context.Error += new EventHandler(Application_ErrorHandle);

               

            }

            #endregion

        }

     

    以上代码向HttpApplicationApplication_Error时间绑定一个处理函数Application_ErrorHandle当程序发生错误时,就会自动执行Application_Error函数,将错误信息输出。

    随后将ErrorProcessHttpModule项目进行编译,得到一个ErrorProcessHttpModule.dll

    如果你的那个程序没有异常处理机制,而又需要查看异常信息,我们就可以将这个dll 文件copy到该程序的bin目录,并修改这个项目的web.config,为它的<httpModules>节点添加元素,如下:

    <httpModules>
        
    <add name="ErrorProcessHttpModule" type="ErrorProcessHttpModule.ErrorProcessHttpModule, ErrorProcessHttpModule"/>
    </httpModules>


    大功告成,这样当程序出错时,就会自动输出异常信息了。

    嗯,用此种方式输出异常信息,记着要把customErrors节点得mode改成On,否则程序会议asp.net默认的方式显示异常信息的。

  • 相关阅读:
    java基础部分的一些有意思的东西。
    antdvue按需加载插件babelpluginimport报错
    阿超的烦恼 javaScript篇
    .NET E F(Entity Framework)框架 DataBase First 和 Code First 简单用法。
    JQuery获得input ID相同但是type不同的方法
    gridview的删除,修改,数据绑定处理
    jgGrid数据格式
    Cannot read configuration file due to insufficient permissions
    Invoke action which type of result is JsonResult on controller from view using Ajax or geJSon
    Entity model数据库连接
  • 原文地址:https://www.cnblogs.com/windinsky/p/1528387.html
Copyright © 2011-2022 走看看