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
        }
    }
    
  • 相关阅读:
    Tiny_4412的NFS挂载
    tiny4412学习一:编译uboot,体验裸机
    开通博客,记录历程,开启新的征程
    mysql 多表联合做运算(求俩点的距离)
    golang gin框架使用图形验证码
    js rgb和16进制相互转换
    [转载] Centos7的安装、Docker1.12.3的安装,以及Docker Swarm集群的简单实例
    openstack golang sdk使用
    sendcloud golang 发送短信 示例代码
    Harbor配置https,并安装内容信任插件(notary)
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1627918.html
Copyright © 2011-2022 走看看