2013-01-07 25 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); 
     } 
    }