I want to capture all the requests going to *.jpg
files on my server. To do so, I have created an HttpHandler whose code is as follows:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Globalization;
namespace MyHandler
{
public class NewHandler : IHttpHandler
{
public NewHandler()
{}
public void ProcessRequest(System.Web.HttpContext ctx)
{
HttpRequest req = ctx.Request;
string path = req.PhysicalPath;
string extension = null;
string contentType = null;
extension = Path.GetExtension(path).ToLower();
switch (extension)
{
case ".gif":
contentType = "image/gif";
break;
case ".jpg":
contentType = "image/jpeg";
break;
case ".png":
contentType = "image/png";
break;
default:
throw new NotSupportedException("Unrecognized image type.");
}
if (!File.Exists(path))
{
ctx.Response.Status = "Image not found";
ctx.Response.StatusCode = 404;
}
else
{
ctx.Response.Write("The page request is " + ctx.Request.RawUrl.ToString());
StreamWriter sw = new StreamWriter(@"C:
equestLog.txt", true);
sw.WriteLine("Page requested at " + DateTime.Now.ToString()
+ ctx.Request.RawUrl); sw.Close();
ctx.Response.StatusCode = 200;
ctx.Response.ContentType = contentType;
ctx.Response.WriteFile(path);
}
}
public bool IsReusable{get {return true;}}
}
}
After compiling this and adding it to my web application's Bin
directory as a deference, I added the following in my web.config
file:
<system.web>
<httpHandlers>
<add verb="*" path="*.jpg" type="MyHandler.NewHandler,MyHandler"/>
</httpHandlers>
</system.web>
Then I also modified the IIS settings Home Directory -> Application Configuration
and added aspnet_isapi.dll
for the .jpg
extension.
In the Handler, I have tried to write some stuff in the log file which I am creating in the C drive, but it is not writing to the log file and I am unable to find the bug.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…