3

*.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

Handler で、C ドライブに作成しているログ ファイルに何かを書き込もうとしましたが、ログ ファイルに書き込めず、バグを見つけることができません。

4

3 に答える 3

3
<httpHandlers>
   <add verb="" path=".jpg" type="MyHandler.NewHandler,MyHandler"/>
</httpHandlers> 

これは、stackoverflow の単なるレイアウトの問題ですか、それともアスタリスク (*) を省略しましたか?

<httpHandlers>
   <add verb="*" path="*.jpg" type="MyHandler.NewHandler,MyHandler"/>
</httpHandlers> 

アスタリスクが欠落していない場合は、FirefoxのFirebugで [ネットワーク] タブを表示しようとします (または、http デバッグ プロキシであるFiddlerを使用します)。呼び出しから取得した HTTP 応答コードは何ですか?

于 2008-12-22T10:33:06.267 に答える
2

アプリケーションを実行しているユーザーは C:\ にアクセスできますか? 通常はそうではありません。ルート ディレクトリへのアプリケーション コンテキスト アクセスを許可すると、大きなセキュリティ リスクが生じます。

代わりに、c:\logs などの特定のディレクトリを作成し、ASP.NET アプリケーション プールのユーザー アカウントにそのディレクトリのみに対する完全な権限を与えます。

于 2008-12-22T10:30:46.443 に答える