天天看點

HttpHandler初探 - 頁面上輸出圖像

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;

            }

    }

}

然後在顯示圖檔的頁面中将<img>的源指向該ashx檔案,aspx檔案代碼如下:

<div>

    <img src="picHandler.ashx" />

</div>

方法二(WebConfig映射):

首先建立一個實作IHttpHandler接口的類,代碼如下:

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>

HttpHandler初探 - 頁面上輸出圖像

  <httpHandlers>

HttpHandler初探 - 頁面上輸出圖像

    <add verb="*" path="MyImage" type="MyPicHandler, App_Code" />

  </httpHandlers>

</system.web>

最後在page頁面中将<img>的源指向webconfig檔案中映射的别名,既path後面的名字,page代碼如下:

    <img src="MyImage" />

繼續閱讀