简体   繁体   中英

Displaying image from db & OutputStream Exceptions ASP.NET/C#

Good night-morning-evening-etc ^_^

I'm getting problems while trying to display an image in asp:Image (using Web Forms), stored in a db as byte[] - found a lot of rather clear answers, how to do it, so now I have a handler:

public class ShowImageHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //creating object, working with db
        var core = new CoreHolder();
        var picture = core.PictureRepository.Read(Convert.ToInt32(context.Request.QueryString["id"]))
        context.Response.Clear();
        context.Response.ContentType = picture.PictureMimeType;
        //trying to write byte[]
        context.Response.BinaryWrite(picture.PictureData);
        context.Response.End();
    }

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

...and such strings in my .aspx page:

<asp:Image ID="Image1" runat="server" ImageUrl="~/ShowImageHandler.ashx?id=<%#:Item.ID %>" />
<asp:Image ID="Image1" runat="server" ImageUrl="~/ShowImageHandler.ashx?id=1>" />

The problems are: ok, the program enters the ProcessRequest with id, and in case of the second asp-image string it finds the pic with data, but even before trying to BinaryWrite I can see, that there are exeptions in context.Response.OutputStream: length,position - System.NotSupportedExeption, Read/WriteTimeout - System.InvalidOperationExeption. In case of the first string (it's used in ListView ItemTemplate) the OutputStream problem stays + all crushes on trying to get the id from the query string.

Help, please)

The errors you see in the debugger for context.Response.OutputStream.Length and Position don't matter. You can only write to that stream so the exceptions you see in the debugger display are expected.

Your code looks fine so my guess is that if you look at the URL, the value for your id querystring argument will not be an integer. You are probably getting a FormatException when you try to convert it to an integer.

You should test the handler by putting the url "ShowImageHandler.ashx?id=1" in your browser's address bar instead of using an <img /> tag. That way if there is an exception you can get a real stack trace instead of just seeing a broken image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM