2013-01-07 22 views
0

我有一个使用ImageHandler输出图像的asp.net web窗体应用程序。基本上要防止水蛭,但也要从另一台服务器上获取图像文件。ASP.NET ImageHandler可以输出Url的内容

这里的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路径访问。我做错了什么,完全可以做到这一点?

干杯

+0

如果我正确理解您的方案,可以使用WebClient类http://msdn.microsoft.com/en-us/library/system.net .webclient.aspx在外部服务器上为您的图像发出HTTP请求,然后在您对客户端的响应中发送该请求。这样,图像的实际URL将对最终用户是不可见的,并且您没有必须使用UNC路径的限制。 – geedubb

+0

其实我找到了另一个解决问题的方法。在重写路径的最后,我调用Response.Redirect。在那里,问题解决了。感谢输入的人。 –

回答

0

当你在电话会议上对这个处理程序 - 那么你没有任何更多的改写你的路径的能力,因为我看到你努力去做。

重写路径就是与IIS和asp.net,要http://www.url.com/one/page1.aspx呼叫例如由http://www.url.com/someotherpage.aspx?id=one

担任你们都准备好不是你的数据的最终处理,还有你必须阅读文件并将其发送到浏览器,例如:

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); 
     } 
    }