ASP.NET处理底层HTTP请求有2种方式:
1)HttpModule 2) HttpHandler
今天我们来看一下HttpHandler的基本应用。
场景:利用HttpHandler在页面上输出一张图像。
在项目中添加HttpHandler的方法有2种:
一种是利用VS2008自带的Generic Handler模板添加扩展名为.ashx的文件。
另一种是利用WebConfig文件中的HttpHandler映射。
方法一(ashx模板):
首先利用VS2008自带的Generic Handler模板添加扩展名为.ashx的文件,
ashx代码如下:
using
System;
using System.Web;
namespace AspNet35.Advanced
{
public class picHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = " image/jpeg " ;
context.Response.WriteFile( " ../Images/Garden.jpg " );
}
public bool IsReusable
{
get
{
return false ;
}
}
}
}
using System.Web;
namespace AspNet35.Advanced
{
public class picHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = " image/jpeg " ;
context.Response.WriteFile( " ../Images/Garden.jpg " );
}
public bool IsReusable
{
get
{
return false ;
}
}
}
}
然后在显示图片的页面中将<img>的源指向该ashx文件,aspx文件代码如下:
<
div
>
< img src ="picHandler.ashx" />
</ div >
< img src ="picHandler.ashx" />
</ div >
方法二(WebConfig映射):
首先建立一个实现IHttpHandler接口的类,代码如下:
using
System.Web;
public class MyPicHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = " image/jpeg " ;
context.Response.WriteFile( " ~/Images/Sea.jpg " );
}
public bool IsReusable
{
get
{
return false ;
}
}
}
public class MyPicHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = " image/jpeg " ;
context.Response.WriteFile( " ~/Images/Sea.jpg " );
}
public bool IsReusable
{
get
{
return false ;
}
}
}
然后在WebConfig文件中映射该类,Web.config代码如下:
<
system.web
>
< httpHandlers >
< add verb ="*" path ="MyImage" type ="MyPicHandler, App_Code" />
</ httpHandlers >
</ system.web >
< httpHandlers >
< add verb ="*" path ="MyImage" type ="MyPicHandler, App_Code" />
</ httpHandlers >
</ system.web >
最后在page页面中将<img>的源指向webconfig文件中映射的别名,既path后面的名字,page代码如下:
<
div
>
< img src ="MyImage" />
</ div >
< img src ="MyImage" />
</ div >