Imagehandler不显示来自远程请求的图像

时间:2012-08-06 07:46:13

标签: c# asp.net handler

您好我写了这个图片处理程序代码,它在我的本地工作正常,并在页面中显示图像,现在我已将其上传到主机上,当我从远程请求页面时,图像不会显示在图像中控制 !有什么帮助吗?!

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

using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web;

public class Handler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IranQRDBConnectionString"].ConnectionString);
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            string TableName = context.Session["TableToQuery"].ToString();
            string ID = context.Session["ID"].ToString();

            SqlCommand comm = new SqlCommand("SELECT * FROM " + TableName + " WHERE ID=" + ID, conn);

            conn.Open();
            SqlDataReader dr = comm.ExecuteReader();
            dr.Read();
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite((byte[])dr["Image"]);
            conn.Close();

        }
        catch
        {
            SqlCommand comm = new SqlCommand("SELECT * FROM DefaultImage WHERE ID=1", conn);

            conn.Open();
            SqlDataReader dr = comm.ExecuteReader();
            dr.Read();
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite((byte[])dr["Image"]);
            conn.Close();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

my connectionstring:

    <add name="ConnectionString" connectionString="Data Source=myDatasource;Initial Catalog=DB;User Id=myusername;Password=mypassword"
   providerName="System.Data.SqlClient" />

这是我展示图像的数据主义者:

                                                                                                                                                                                        '/&gt;                                                                                                                                                                                                         “&GT;                                                                                                                                                                     

我检查了我的数据库,数据插入正确,文本数据回发到我的页面,但只有图像没有显示

这是我的webconfig的一部分:

<system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
        <remove name="ScriptModule"/>
        <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </modules>
    <handlers>
        <remove name="WebServiceHandlerFactory-Integrated"/>
        <remove name="ScriptHandlerFactory"/>
        <remove name="ScriptHandlerFactoryAppServices"/>
        <remove name="ScriptResource"/>
        <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </handlers>
</system.webServer>

2 个答案:

答案 0 :(得分:1)

首先,您并不总是处理数据库连接。如果 catch 块中出现异常,则不会关闭该连接。此外,如果在 conn.Open()之后的 try 块中抛出异常,您将最终打开连接两次。 始终使用使用语句来管理实现 IDisposable 的资源的生命周期。

第二,捕捉异常作为回归默认图像的手段并不是好的风格。实际上,您可能正在泄漏资源(我不清楚在正确抛出异常的位置读取代码)。

至于核心问题,我不相信有足够的信息来回答在部署代码后图像没有显示的原因。

您的数据库连接字符串是否正确?你从第一次

获得了什么?
comm.ExecuteReader()

如果抛出异常,那么Exception和where?

如果您在代码中添加日志记录来回答这些问题,那么问题的根源很可能会变得明显。如果没有,请用这些答案更新您的问题。

答案 1 :(得分:1)

除非使用Seesion,否则为什么不尝试使用查询字符串。这是我的代码,其中使用查询字符串,我从数据库中获取图像,而不必在您的本地文件夹中创建所需图像的任何实例。跳这有帮助。

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

using System;
using System.Web;
using System.Configuration;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class DisplayImg : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string theID;
        if (context.Request.QueryString["id"] != null)
            theID = context.Request.QueryString["id"].ToString();
        else
            throw new ArgumentException("No parameter specified");

        context.Response.ContentType = "image/jpeg";
        Stream strm = DisplayImage(theID);
        byte[] buffer = new byte[2048];
        int byteSeq = strm.Read(buffer, 0, 2048);

        while (byteSeq > 0)
        {
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 2048);
        }
    }

    public Stream DisplayImage(string theID)
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SERVER"].ConnectionString.ToString());
        string sql = "SELECT Server_image_icon FROM tbl_ServerMaster WHERE server_Code = @ID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", theID);
        connection.Open();
        object theImg = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])theImg);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
} 

只需在CS代码中添加一行

即可
UploadImg.ImageUrl = "~/DisplayImg.ashx?id=" + code;