zoukankan      html  css  js  c++  java
  • 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
    {
        /// <summary>
        /// 这个模块的作用,是在页面的顶部和底部分别输出一段文字
        /// 作者:陈希章
        /// </summary>
    
        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("顶部的文字<hr />");
                    
                };
    
    
    
                context.EndRequest += (o2, e2) =>
                {
                    HttpApplication app = (HttpApplication)o2;
                    if (app.Request.Url.AbsolutePath.EndsWith("aspx"))
                        app.Context.Response.Write("<hr />底部的文字");
    
                    //可以把当前用户读取到,并且记录他的访问事件
                    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
        }
    }
    
  • 相关阅读:
    hibernateValidator 升级
    java异常
    reids过期键三种删除策略
    hashmap源码探究
    http知识梳理1
    GregorianCalendar类的使用
    计算机网络笔记
    List的toArray方法
    实习周记一
    vue指令详解
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1627918.html
Copyright © 2011-2022 走看看