c# - 如何将 .ashx 处理程序与 asp :Image object? 一起使用

标签 c# asp.net image ashx

我有一个 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/

相关文章:

c# - 如何在Azure角色中缓存数据库读取?

asp.net - IIS 7 如何将客户端证书映射到数据库中的用户帐户?

jquery - 使 DIV 不显示在其容器外

css:将图像链接到 url

php - 我的 config.php 有什么问题?

html - 加载大量图像并将前 100 张设置为可见

c# - WCF 服务引用生成自己的契约接口(interface),不会重用我的

c# - 在 C# 中使用反射进行转换

c# - 在实现中设置私有(private) Setter 的模拟 void 方法

asp.net - 如何防止 DIV 中文字中的 HTML 代码影响外部页面样式