我想捕获所有发送到*.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;}}
}
}
在编译它并将其添加到我的 Web 应用程序的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 驱动器中创建的日志文件中写入一些内容,但它没有写入日志文件,我无法找到错误。