[英]Create ASP.Net Handler to return Image as Bytes
我正在尋找創建一個處理程序來返回基於傳遞的id的圖像,我沒有創建自己的一個之前和當我創建它時它提到它必須在IIS注冊。 這個項目分發給很多客戶,我是否需要更改每個客戶端的IIS或者是否有某種方式來處理這個或者替代處理程序?
編輯:響應下面,這是我創建(但尚未測試),所以我需要更改IIS或web.config中的任何內容嗎?
public class Photos : IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
//write your handler implementation here.
var img = Image.FromFile(@"C:\Projects\etc\logo.jpg");
context.Response.ContentType = "image/jpeg";
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
#endregion
}
您可以創建一個繼承IHttpHandler
的類,並在其中獲取id(來自查詢字符串或類似字符串),處理請求並返回二進制數據。 不應該用IIS注冊它...
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//Get Id from somewhere
//Get binary data
context.Response.ContentType = "application/octet-stream";
context.Response.BinaryWrite(bytes);
}
}
您可以為項目添加通用處理程序 ( .ashx
文件)。 它將為您提供一個帶有代碼隱藏的文件,如下所示(摘錄):
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
您可以使用context
來獲取查詢字符串或路由參數,並使用context.Response
屬性來編寫圖像。 將返回的內容類型更改為您的圖像內容類型,然后進行設置。
您可以將圖像src
設置為: "Handler1.ashx?id=12345"
,或者您可以添加指向處理程序的漂亮URL路由。
無需為此配置IIS。
你可以看看這篇關於Handlers的博文, http://www.dotnetperls.com/ashx ,我認為這與你想做的非常接近。
httphandlers在網站的web.config中注冊,如果您使用網站分發配置文件,則無需更改iis配置
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.