ASP.NET : 自定义HttpModule的时候要注意的问题

今天再次讲到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 } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值