IHttpModule相對來說,是一個網頁的添加
IHttpHandler相對來說,卻是網頁的替換
先建一個HandlerDemo的類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Http_Handler_Model
{
public class HandlerDemo : IHttpHandler
{
/*
這個IsReusable的true是可以提高效率但是,會線程不安全
IHttpHandler實例可以再次使用
false,會安全一些,效率會低一些
IHttpHandler的實例就不能使用
*/
public bool IsReusable => true;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
context.Response.Write("<h2>這是HandlerDemo做出來的</h2>");
}
}
}
在建一個Module的類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Http_Handler_Model
{
public class Modules : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
//添加一個開始的事件,和一個結束的事件
context.BeginRequest += Context_BeginRequest;
context.EndRequest += Context_EndRequest;
}
private void Context_EndRequest(object sender, EventArgs e)
{
HttpApplication httpApplication = sender as HttpApplication;
httpApplication.Response.Write("<h2>這是開始頁面</h2>");
}
private void Context_BeginRequest(object sender, EventArgs e)
{
HttpApplication httpApplication = sender as HttpApplication;
httpApplication.Response.Write("<h2>這是結束頁面</h2>");
}
}
}
把這兩個類建完了,就是添加到配置文件中
打開你當前項目的這個配置文件
添加這些
這裏面配置了handlers和modules
type的值是:命名空間.(點)你的類
path的值是:你的作用域,我這裏的作用域是某個文件夾下面的aspx
<system.webServer>
<handlers>
<add name="handlers" path="Handler_Test/*.aspx" verb="*" type="Http_Handler_Model.HandlerDemo"/>
</handlers>
<modules>
<add name="modules" type="Http_Handler_Model.Modules"/>
</modules>
</system.webServer>
ModuleDemo的aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ModelsDemo.aspx.cs" Inherits="Http_Handler_Model.ModelsDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
這個是modules的樣例
</div>
</form>
</body>
</html>
效果圖
這裏添加了剛纔的Modules類的操作
某個文件夾下面的aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HandlerDemo.aspx.cs" Inherits="Http_Handler_Model.Handler_Test.HandlerDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
這是Test被替換的頁面
</div>
</form>
</body>
</html>
顯示效果
這裏沒有代碼中的這是Test被替換的頁面
,而是HandlerDemo的操作