如何在asp:Image对象中使用.ashx处理程序?

我有一个ashx处理程序:

 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页面中,我有这一行:

  

它背后的C#代码是:

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

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

  

谁能告诉我为什么这不起作用? 不幸的是我昨天才开始使用ASP.NET,我不知道它是如何工作的,所以请尽可能简化解释,谢谢。

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

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

方法而不是。

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

此代码有助于按文件名从指定路径查看图像。
恩。 http://sofzh.miximages.com/c%23/fimageview.png

你可以在你的ASPX html体内使用.ashx。

例:

  

  <%@ WebHandler Language="C#" Class="Fimageview" %> ///  /// Created By Rajib Chowdhury Mob. 01766-306306; Web: http://www.rajibs.tk /// Email: mysuccessstairs@hotmail.com /// 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 ///  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; } } } 

我是原始海报,我终于找到了问题所在。 我所要做的就是改变:

  

至:

  

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

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