locked
HttpHandler Stuck in Redirect Loop - Trying to output image. RRS feed

  • Question

  • User-1496281956 posted

    Hello,

    I recently moved a bunch of images/content to a different folder meaning links are broken this means, i need to process those 404 errors. In this case I have created a custom handler to detect whether the png file (png for example, but also use gifs etc) exists on the server if not, we check if the URL exists in the database if it does we get it's new URL. However this gets stuck in a redirect loop because the new URL also has .png at end. It returns a solid 200 OK but shows no content.

            public void ProcessRequest(HttpContext context)
            {
                bool FileExists = DoesFileExist(context);
    
    
                    if (!FileExists)
                    {
                        //TODO: detect screen and resize..
    
                        string path = context.Request.Url.AbsolutePath;
    
                        //Is it in the database?
                        Redirects URL = RedirectDAL.Retrieve<Redirects>().Where(a => a.OldURL == path).FirstOrDefault();
    
                        if (URL != null)
                        {
                            context.Response.RedirectPermanent("http://intranet/" + URL.NewURL);
    } else { context.Response.StatusCode = 404; } } else { //file exists context.Response.ContentType = "image/png"; context.Response.Write("<img src=\"" + context.Request.Url.AbsolutePath + "\" />"); } } public static bool DoesFileExist(HttpContext context) { var path = context.Request.Url.AbsolutePath; return File.Exists(context.Server.MapPath("~" + path)); }

    How could I solve something like this. Personally i could use cookies/session but that also seems an overkill for something which I did consider simple. This:

     context.Response.Write("<img src=\"" + context.Request.Url.AbsolutePath + "\" />");

    Does not work since the src ends in .png and it executes code again, thus returns 200, but no content.

    Monday, August 11, 2014 5:25 PM

Answers

  • User-1818759697 posted

    Hi,

    context.Response.Write("<img src=\"" + context.Request.Url.AbsolutePath + "\" />");

    You could just try to write the path not including the img tag:

    context.Response.ContentType = "image/jpg";
    context.Response.WriteFile(context.Request.Url.AbsolutePath);

    Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 13, 2014 5:55 AM