我有一个 ashx 处理程序:
<%@ WebHandler Language="C#" Class="Thumbnail" %>
using System;
using System.Web;
public class Thumbnail : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string imagePath = context.Request.QueryString["image"];
// split the string on periods and read the last element, this is to ensure we have
// the right ContentType if the file is named something like "image1.jpg.png"
string[] imageArray = imagePath.Split('.');
if (imageArray.Length <= 1)
{
throw new HttpException(404, "Invalid photo name.");
}
else
{
context.Response.ContentType = "image/" + imageArray[imageArray.Length - 1];
context.Response.Write(imagePath);
}
}
public bool IsReusable
{
get { return true; }
}
}
现在这个处理程序所做的就是获取图像并将其返回。在我的 aspx 页面中,我有这一行:
<asp:Image ID="Image1" runat="server" CssClass="thumbnail" />
它背后的C#代码是:
Image1.ImageUrl = "Thumbnail.ashx?image=../Files/random guid string/test.jpg";
当我查看网页时,没有显示图像,而 HTML 显示的正是我输入的内容:
<img class="thumbnail" src="Thumbnail.ashx?image=../Files%5Crandom guid string%5Cimages%5Ctest.jpg" style="border-width:0px;" />
有人能告诉我为什么这不起作用吗?不幸的是,我昨天才开始使用 ASP.NET,我不知道它是如何工作的,所以请尽可能简单地解释,谢谢。
最佳答案
您正在打印图像的路径而不是实际的图像内容。使用
context.Response.WriteFile(context.Server.MapPath(imagePath));
方法代替。
确保将路径限制在某个安全位置。否则,您可能会引入安全漏洞,因为用户将能够看到服务器上任何文件的内容。
关于c# - 如何将 .ashx 处理程序与 asp :Image object? 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1096122/