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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1096122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:06:28  来源:igfitidea点击:

How do I use an .ashx handler with an asp:Image object?

c#asp.netimageashx

提问by

I have an ashx handler:

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

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

现在这个处理程序所做的就是获取一个图像并返回它。在我的 aspx 页面中,我有这一行:

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

And the C# code behind it is:

它背后的 C# 代码是:

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:

当我查看网页时,图像没有显示,HTML 显示的正是我输入的内容:

<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.

有人能告诉我为什么这不起作用吗?不幸的是,我昨天才开始使用 ASP.NET,我不知道它是如何工作的,所以如果可能的话,请保持解释简单,谢谢。

回答by Mehrdad Afshari

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.

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

回答by Daniel T.

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.

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

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.

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

回答by rktuxyn

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:

此代码有助于从指定路径按文件名查看图像。
前任。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;
        }
    }
}