创建ASP.Net Handler以返回Image作为字节
我正在寻找创建一个处理程序,以返回基于传递的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 }
您可以创建一个inheritanceIHttpHandler
的类,并在其中获取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配置