ASP.NET : 自定义HttpModule的时候要注意的问题
2009-12-19 12:36
323 查看
今天再次讲到HttpModule的问题。这里有一个比较细节的地方:因为Module是所有Request都会处理的,如果在Module中需要往Response中写入内容,则需要考虑根据请求类型进行一些判断。
例如下面这个例子,我们在BeginRequest的时候就输入一些文字。但试想一下,如果Request是一个图片,那么输入这些文字无疑将让图片失效。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using System.Xml.Linq; namespace WebApp { /// /// 这个模块的作用,是在页面的顶部和底部分别输出一段文字 /// 作者:陈希章 /// public class MyModule:IHttpModule { #region IHttpModule 成员 public void Dispose() { } public void Init(HttpApplication context) { context.BeginRequest += (o1, e1) => { //因为Module是每一个Request都会进行处理,所以要考虑一些文件类型(例如图片)的时候,应该要跳过去 HttpApplication app = (HttpApplication)o1; if (app.Request.Url.AbsolutePath.EndsWith("aspx")) app.Response.Write("顶部的文字"); }; context.EndRequest += (o2, e2) => { HttpApplication app = (HttpApplication)o2; if (app.Request.Url.AbsolutePath.EndsWith("aspx")) app.Context.Response.Write("底部的文字"); //可以把当前用户读取到,并且记录他的访问事件 string logFile = app.Server.MapPath("Log.xml"); XDocument doc = null; if (!File.Exists(logFile)) { doc = new XDocument( new XElement("Logs")); } else doc = XDocument.Load(logFile); XElement item = new XElement("Item", new XAttribute("User", app.User.Identity.Name), new XAttribute("Time", DateTime.Now), new XAttribute("Path", app.Request.Path)); doc.Root.Add(item); doc.Save(logFile); }; } #endregion } }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
相关文章推荐
- ASP.NET : 自定义HttpModule的时候要注意的问题
- ASP.Net中自定义HttpModule
- 在ASP.NET MVC 3 中自定义AuthorizeAttribute时需要注意的页面缓存问题
- ASP.Net中自定义Http处理及应用之HttpModule
- ASP.Net中自定义Http处理及应用之HttpModule篇
- ASP.NET-自定义HttpModule与HttpHandler
- ASP.NET-自定义HttpModule与HttpHandler
- 在ASP.NET MVC 3 中自定义AuthorizeAttribute时需要注意的页面缓存问题
- ASP.NET-自定义HttpModule与HttpHandler介绍
- asp.net mvc中在使用async的时候HttpContext为null的问题
- ASP.NET-自定义HttpModule与HttpHandler介绍
- asp.net 2.0下用access开发的时候要注意的问题
- Asp.net Web Applicatoin实现自定义HttpModule拦截异常处理
- asp.net 2.0下用access开发的时候要注意的问题
- asp.net 2.0下用access开发的时候要注意的问题
- ASP.NET使用三层架构时候注意的问题+基础使用
- 解决Asp.net Mvc中使用异步的时候HttpContext.Current为null的方法
- Asp.net使用HttpModule压缩并删除空白Html请求
- ASP.Net中自定义Http处理及应用之HttpModule篇
- 七天学会ASP.NET MVC (六)——线程问题、异常处理、自定义URL