Я хочу перехватить все запросы к файлам *.jpg
на моем сервере. Для этого я создал HttpHandler, код которого выглядит следующим образом:
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:\requestLog.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;}}
}
}
После компиляции и добавления его в каталог Bin
моего веб-приложения в качестве ссылки я добавил в свой файл web.config
следующее:
<system.web>
<httpHandlers>
<add verb="*" path="*.jpg" type="MyHandler.NewHandler,MyHandler"/>
</httpHandlers>
</system.web>
Затем я также изменил настройки IIS Home Directory -> Application Configuration
и добавил aspnet_isapi.dll
для расширения .jpg
.
В обработчике я попытался записать кое-что в файл журнала, который я создаю на диске C, но он не записывает в файл журнала, и я не могу найти ошибку.