Creare un HttpHandler per caricare immagini
Scritto da
Alessandro Mostarda il
lunedì 22 novembre 2010
•
Linguaggio:
• Livello: 200
Questo esempio mostra come creare un HttpHandler che consente di
caricare delle immagini da una directory non situtata
all'interno del sito.
Per prima cosa occorre creare una classe che implementi
l'interfaccia IHttpHandler:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
namespace DomusHttpHandlerExample
{
public class HttpImageHandler:IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
string fileName = ConfigurationManager.AppSettings["ImageDir"] + context.Request.QueryString["file"];
using (var img = new Bitmap(fileName))
{
context.Response.ContentType = "image/jpeg";
context.Response.BufferOutput = false;
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
context.Response.End();
}
}
#endregion
}
}
Dopo di che dobbiamo registrare l'HttpHandler nel
web.config:
<httpHandlers>
<add verb="*" path="*.img" type="DomusHttpHandlerExample.HttpImageHandler"/>
</httpHandlers>
P.S. il tag HttpHandler si trova sotto il nodo System.Web
Per far funzionare il tutto dobbiamo anche registare
l'estensione *.Img(parametro presente nel valore Path
del file di configurazione) all'interno di IIS. Quindi andare sotto
la voce "Mapping gestori" o "Handler Mappings" del sito su IIS
ed aggiungere tale voce.
Per testare l'handler, occorre creare un tag
IMG,all'interno della nostra pagina, con il seguente
valore nell'attributo src:
<img src="HttpImageHandler.img?file=prova.jpg" alt="Test image" />
Tags: ASP.NET,HttpHandler