0

我有一个使用 ImageHandler 输出图像的 asp.net Web 表单应用程序。基本上是为了防止盗取,但也是为了从另一台服务器获取图像文件。

下面是 ProcessRequest 的实现:

public void ProcessRequest(HttpContext ctx)
    {
        HttpRequest req = ctx.Request;
        string path = req.PhysicalPath.ToLower();
        string extension = Path.GetExtension(path);

        if (req.UrlReferrer != null && req.UrlReferrer.Host.Length > 0)
        {
            if (CultureInfo.InvariantCulture.CompareInfo.Compare(req.Url.Host, req.UrlReferrer.Host, CompareOptions.IgnoreCase) != 0)
            {
                path = ctx.Server.MapPath("~/images/noimage.jpg");
            }
        } 

        // Rewrite path if not in production
        if (imagePath != null)
        {
            if (path.Length > path.IndexOf("\\images\\", StringComparison.Ordinal) + 7)
            {
                string end = path.Substring(path.IndexOf("\\images\\", StringComparison.Ordinal) + 7);
                path = string.Concat(imagePath, end).Replace("\\", "/");
            }
        }

        string contentType;

        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.StatusCode = 200;
            ctx.Response.ContentType = contentType;
            ctx.Response.WriteFile(path);
        }
    }

上面的代码失败是因为我想将路径重写为 url 而不是文件路径。我想重写的原因是因为实际的图像文件在另一台服务器上,不能通过 UNC 路径访问。我做错了什么,有可能做到这一点吗?

干杯

4

1 回答 1

0

When you are on the call for this handler - then you do not have any more the ability to rewrite your path as I see that you try to do.

The rewrite path is to say to IIS and asp.net that a call for example to http://www.url.com/one/page1.aspx is served by the http://www.url.com/someotherpage.aspx?id=one

You are all ready not on the final processing of your data, there you must read the file and send it to the browser, for example as:

 public void ProcessRequest(HttpContext context)
    {
      // your first code
      // ...
       if (!File.Exists(path))
        {
            ctx.Response.Status = "Image not found";
            ctx.Response.StatusCode = 404;
        }
        else
        {
            // load here the image 
            ....
            // and send it to browser
            ctx.Response.OutputStream.Write(imageData, 0, imageData.Length);
        }
    }
于 2013-01-07T15:24:24.003 回答