动态注册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() : ;
if (code != )
{
} //记录到日志文件 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));
}
}
}
}
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");
}
}
参考内容 http://www.cnblogs.com/TomXu/p/3756846.html
动态注册HttpModule管道,实现global.asax功能的更多相关文章
- Mvc动态注册HttpModule详解
序言 注册Httpmodule可以让我们使用HttpApplication对象中的处理管道事件.目前大家所熟知的应该有2种方式来使用HttpApplication对象中的处理管道事件.第一种是通过Gl ...
- 你必须知道ASP.NET知识------关于动态注册httpmodule(对不起汤姆大叔)
一.关于动态注册的问题 很多人看过汤姆大叔的MVC之前的那点事儿系列(6):动态注册HttpModule ,其实汤姆大叔没有发现httpmodule动态注册的根本机制在哪里. 亦即:怎么动态注册?为什 ...
- 不使用配置文件动态注册HttpModule
在asp.net 4.0中,提供了一种不通过修改配置文件注册Module的方法.从.net3.5开始,新提供的PreApplicationStartMethodAttribute特性可以应用在程序集上 ...
- MVC之前的那点事儿系列(6):动态注册HttpModule
文章内容 通过前面的章节,我们知道HttpApplication在初始化的时候会初始化所有配置文件里注册的HttpModules,那么有一个疑问,能否初始化之前动态加载HttpModule,而不是只从 ...
- 动态注册HttpModule
动态注册HttpModule 2014-06-05 08:58 by 汤姆大叔, 757 阅读, 4 评论, 收藏, 编辑 文章内容 通过前面的章节,我们知道HttpApplication在初始化的时 ...
- MVC源码解析 - 配置注册 / 动态注册 HttpModule
本来这一篇, 是要继续 Pipeline 的, 但是在 Pipeline之前, 我看到了InitModules()方法, 所以决定, 在中间穿插一篇进来. 这一篇来讲一下 IHttpModule 的加 ...
- 在Asp.net 4.0 中动态注册HttpModule
using System; using System.Web; using Microsoft.Web.Infrastructure; namespace MvcApplication1 { publ ...
- ASP.NET MVC中注册Global.asax的Application_Error事件处理全局异常
在ASP.NET MVC中,通过应用程序生命周期中的Application_Error事件可以捕获到网站引发的所有未处理异常.本文作为学习笔记,记录了使用Global.asax文件的Applicati ...
- MEF在WCF REST中实际应用2(Global.asax注册)
IOCContainer文件: public class IOCContainer { /// <summary> /// 容器 /// </summary> public s ...
随机推荐
- Codeforces Round #270 A. Design Tutorial: Learn from Math【数论/埃氏筛法】
time limit per test 1 second memory limit per test 256 megabytes input standard input output standar ...
- Python的程序结构[2] -> 类/Class[5] -> 内建类 bytes 和 bytearray
内建类 bytes 和 bytearray / Built-in Type bytes and bytearray 关于内建类 Python的内建类 bytes 主要有以下几点: class byte ...
- 树的直径【p3629】[APIO2010]巡逻
Description 在一个地区中有 n 个村庄,编号为 1, 2, ..., n.有 n – 1 条道路连接着这些村 庄,每条道路刚好连接两个村庄,从任何一个村庄,都可以通过这些道路到达其 他任一 ...
- hdu 1425 Happy 2004
题目链接 hdu 1425 Happy 2004 题解 题目大意: 求 \[\sum_{d|2004^{x}}d\ mod\ 29\] 记为\(s(2004^x)\) \(sum(2004^{x})= ...
- [CTSC2018]假面(概率DP)
考场上以为CTSC的概率期望题都不可做,连暴力都没写直接爆零. 结果出来发现全场70以上,大部分AC,少于70的好像极少,感觉血亏. 设a[i][j]表示到当前为止第i个人的血量为j的概率(注意特判血 ...
- [COCI2017-2018 Contest5] Birokracija
题目描述 Mirko has become CEO of a huge corporation. This corporation consists of N people, labeled fro ...
- 六. 异常处理5.多重catch语句的使用
某些情况,由单个代码段可能引起多个异常.处理这种情况,你可以定义两个或更多的catch子句,每个子句捕获一种类型的异常.当异常被引发时,每一个catch子句被依次检查,第一个匹配异常类型的子句执行.当 ...
- 如何快速搜索SQL数据库数据和对象
原文 如何快速搜索SQL数据库数据和对象 Frequently, developers and DBAs need to search databases for objects or data. I ...
- Overview of iOS Crash Reporting Tools: Part 2/2
Thanks for joining me for the second part of this two-part series on crash reporting services! The f ...
- 重要的ui组件——Behavior
v7包下的组件类似CoordinatorLayout推出也有一段时间了,大家使用的时候应该会体会到其中很多的便利,今天这篇文章带大家来了解一个比较重要的ui组件——Behavior.从字面意思上就可以 ...