httpHandlers和httpModules接口介绍 (3)

第三步:在Init事件中注册PreRequestHandlerExecute事件,并实现事件处理方法

class AuthenticModule:IHttpModule
{
public void Dispose(){}
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute +
= new EventHandler(context_PreRequestHandlerExecute);
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication ha = (HttpApplication)sender;
string path = ha.Context.Request.Url.ToString();
int n = path.ToLower().IndexOf("Login.aspx"); 
if (n == -1) //是否是登录页面,不是登录页面的话则进入{}
{
if (ha.Context.Session["user"] == null) 
//是否Session中有用户名,若是空的话,转向登录页。
{
ha.Context.Response.Redirect("Login.aspx?source=" + path);
}
}
}
}

第四步:在Login.aspx页面的“登录”按钮中加入下面代码

protected void Button1_Click(object sender, EventArgs e)
{
if(true)//判断用户名密码是否正确
{ 
if (Request.QueryString["source"] != null)
{
string s = Request.QueryString["source"].ToLower().ToString();  
 //取出从哪个页面转来的
Session["user"] = txtUID.Text;
Response.Redirect(s); //转到用户想去的页面
}
else
{
Response.Redirect("main.aspx");//默认转向main.aspx
}
} 
}

第五步:在Web.Conofig中注册一下这个HttpModule模块

<httpModules>
   <add name="TestModule" type
="ClassLibrary831.TestModule,ClassLibrary831"></add>
  </httpModules>

3、多模块的操作

如果定义了多个HttpModule,在web.config文件中引入自定义HttpModule的顺序就决定了多个自定义HttpModule在处理一个HTTP请求的接管顺序。

HttpHandler

HttpHandler是HTTP请求的处理中心,真正地对客户端请求的服务器页面做出编译和执行,并将处理过后的信息附加在HTTP请求信息流中再次返回到HttpModule中。

HttpHandler与HttpModule不同,一旦定义了自己的HttpHandler类,那么它对系统的HttpHandler的关系将是“覆盖”关系。

IHttpHandler接口声明
public interface IHttpHandler
{
bool IsReusable { get; }
public void ProcessRequest(HttpContext context); 
//请求处理函数
}

示例:把硬盘上的图片以流的方式写在页面上
class TestHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
FileStream fs = new FileStream
(context.Server.MapPath("worm.jpg"), FileMode.Open);
byte[] b = new byte[fs.Length];
fs.Read(b, 0, (int)fs.Length);
fs.Close();
context.Response.OutputStream.Write(b, 0, b.Length);
}
public bool IsReusable
{
get
{
return true;
}
}
}
原文地址:https://www.cnblogs.com/sntetwt/p/1980392.html