我有一个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; }
}
}
Run Code Online (Sandbox Code Playgroud)
现在这个处理程序所做的就是获取一个图像并将其返回.在我的aspx页面中,我有这一行:
<asp:Image ID="Image1" runat="server" CssClass="thumbnail" />
Run Code Online (Sandbox Code Playgroud)
它背后的C#代码是:
Image1.ImageUrl = "Thumbnail.ashx?image=../Files/random guid string/test.jpg";
Run Code Online (Sandbox Code Playgroud)
当我查看网页时,图像没有显示,HTML显示我输入的内容:
<img class="thumbnail" src="Thumbnail.ashx?image=../Files%5Crandom guid string%5Cimages%5Ctest.jpg" style="border-width:0px;" />
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我为什么这不起作用?不幸的是我昨天才开始使用ASP.NET,我不知道它是如何工作的,所以请尽可能简化解释,谢谢.
您正在打印图像的路径而不是实际的图像内容.使用
context.Response.WriteFile(context.Server.MapPath(imagePath));
Run Code Online (Sandbox Code Playgroud)
方法而不是.
确保将路径限制在某个安全位置.否则,您可能会引入安全漏洞,因为用户可以看到服务器上任何文件的内容.