如何将 .ashx 处理程序与 asp:Image 对象一起使用?

发布于 2024-07-26 14:54:34 字数 1459 浏览 6 评论 0原文

我有一个 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,我不知道它是如何工作的,所以请尽可能保持简单的解释,谢谢。

I have an ashx handler:

<%@ 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; }
    }
}

For now all this handler does is get an image and return it. In my aspx page, I have this line:

<asp:Image ID="Image1" runat="server" CssClass="thumbnail" />

And the C# code behind it is:

Image1.ImageUrl = "Thumbnail.ashx?image=../Files/random guid string/test.jpg";

When I view the web page, the images are not showing and the HTML shows exactly what I typed:

<img class="thumbnail" src="Thumbnail.ashx?image=../Files%5Crandom guid string%5Cimages%5Ctest.jpg" style="border-width:0px;" />

Can someone tell me why this isn't working? Unfortunately I only started working with ASP.NET yesterday and I have no idea how it works, so please keep the explanations simple if possible, thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心作怪 2024-08-02 14:54:34

您正在打印图像的路径而不是实际的图像内容。 改用

context.Response.WriteFile(context.Server.MapPath(imagePath));

方法。

确保将路径限制到某个安全位置。 否则,您可能会引入安全漏洞,因为用户可以看到服务器上任何文件的内容。

You are printing out the path to the image instead of the actual image contents. Use

context.Response.WriteFile(context.Server.MapPath(imagePath));

method instead.

Make sure you restrict the path to some safe location. Otherwise, you might introduce security vulnerabilities as users would be able to see contents of any file on the server.

空宴 2024-08-02 14:54:34

此代码有助于从指定路径按文件名查看图像。
前任。 http://onlineshoping.somee.com/Fimageview.ashx?FImageName=FrozenToront.Jpg

并且您可以在 ASPX html 正文中使用 .ashx。

示例:

<image src="/Timageview.ashx?TImageName=FrozenToront.Jpg"
                                      width="100" height="75" border="1"/>

    <%@
        WebHandler Language="C#"
        Class="Fimageview"
    %>

    /// <summary>
    /// Created By Rajib Chowdhury Mob. 01766-306306; Web: http://www.rajibs.tk
    /// Email: [email protected]
    /// FB: https://www.facebook.com/fencefunny
    /// 
    /// Complete This Page Coding On Fabruary 12, 2014
    /// Programing C# By Visual Studio 2013 For Web
    /// Dot Net Version 4.5
    /// Database Virsion MSSQL Server 2005
    /// </summary>

    using System;
    using System.IO;
    using System.Web;

public class Fimageview : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {

        HttpResponse r = context.Response;
        r.ContentType = "image/png";
        string file = context.Request.QueryString["FImageName"];
        if (string.IsNullOrEmpty(file))
        {
            context.Response.Redirect("~/default");//If RequestQueryString Null Or Empty
        }
        try
        {
            if (file == "")
            {
                context.Response.Redirect("~/Error/PageNotFound");
            }
            else
            {
                r.WriteFile("/Catalog/Images/" + file); //Image Path If File Name Found
            }
        }
        catch (Exception)
        {
            context.Response.ContentType = "image/png";
            r.WriteFile("/yourImagePath/NoImage.png");//Image Path If File Name Not Found
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

This code help to Viewing image by File name From Specified Path.
ex. http://onlineshoping.somee.com/Fimageview.ashx?FImageName=FrozenToront.Jpg

And You may use .ashx in your ASPX html body.

Example:

<image src="/Timageview.ashx?TImageName=FrozenToront.Jpg"
                                      width="100" height="75" border="1"/>

    <%@
        WebHandler Language="C#"
        Class="Fimageview"
    %>

    /// <summary>
    /// Created By Rajib Chowdhury Mob. 01766-306306; Web: http://www.rajibs.tk
    /// Email: [email protected]
    /// FB: https://www.facebook.com/fencefunny
    /// 
    /// Complete This Page Coding On Fabruary 12, 2014
    /// Programing C# By Visual Studio 2013 For Web
    /// Dot Net Version 4.5
    /// Database Virsion MSSQL Server 2005
    /// </summary>

    using System;
    using System.IO;
    using System.Web;

public class Fimageview : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {

        HttpResponse r = context.Response;
        r.ContentType = "image/png";
        string file = context.Request.QueryString["FImageName"];
        if (string.IsNullOrEmpty(file))
        {
            context.Response.Redirect("~/default");//If RequestQueryString Null Or Empty
        }
        try
        {
            if (file == "")
            {
                context.Response.Redirect("~/Error/PageNotFound");
            }
            else
            {
                r.WriteFile("/Catalog/Images/" + file); //Image Path If File Name Found
            }
        }
        catch (Exception)
        {
            context.Response.ContentType = "image/png";
            r.WriteFile("/yourImagePath/NoImage.png");//Image Path If File Name Not Found
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
作死小能手 2024-08-02 14:54:34

我是原发帖者,我终于找到了问题所在。 我所要做的就是将: 更改

<asp:Image ID="Image1" runat="server" CssClass="thumbnail" />

为:

<asp:Image ID="Image1" runat="server" CssClass="thumbnail" imageurl='<%# "~/Thumbnail.ashx?image=" + Utilities.ToURLEncoding("~\\Files" + DataBinder.Eval(Container.DataItem, "file_path")) %>' />

标点符号需要更改为其 HTML 等效项,因此反斜杠变为 %5C 等...,否则它将无法工作。

哦,我忘了提,这是在 DataList 中。 奇怪的是,在 DataList 之外使用 Image1.ImageUrl = "Thumbnail.ashx?image=blahblah"; 效果非常好。

I'm the original poster and I finally figured out the problem. All I had to do was change:

<asp:Image ID="Image1" runat="server" CssClass="thumbnail" />

to:

<asp:Image ID="Image1" runat="server" CssClass="thumbnail" imageurl='<%# "~/Thumbnail.ashx?image=" + Utilities.ToURLEncoding("~\\Files" + DataBinder.Eval(Container.DataItem, "file_path")) %>' />

Punctuation needs to be changed to its HTML equivalent, so backslashes become %5C, etc..., or else it won't work.

Oh, I forgot to mention, this is in a DataList. Using Image1.ImageUrl = "Thumbnail.ashx?image=blahblah"; outside of a DataList works perfectly fine, strangely.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文