I have an asp.net web forms application that uses an ImageHandler to output images. Basically to prevent leeching but also to get image files from another server.
Here’s the implementation of ProcessRequest:
public void ProcessRequest(HttpContext ctx)
{
HttpRequest req = ctx.Request;
string path = req.PhysicalPath.ToLower();
string extension = Path.GetExtension(path);
if (req.UrlReferrer != null && req.UrlReferrer.Host.Length > 0)
{
if (CultureInfo.InvariantCulture.CompareInfo.Compare(req.Url.Host, req.UrlReferrer.Host, CompareOptions.IgnoreCase) != 0)
{
path = ctx.Server.MapPath("~/images/noimage.jpg");
}
}
// Rewrite path if not in production
if (imagePath != null)
{
if (path.Length > path.IndexOf("\\images\\", StringComparison.Ordinal) + 7)
{
string end = path.Substring(path.IndexOf("\\images\\", StringComparison.Ordinal) + 7);
path = string.Concat(imagePath, end).Replace("\\", "/");
}
}
string contentType;
switch (extension)
{
case ".gif":
contentType = "image/gif";
break;
case ".jpg":
contentType = "image/jpeg";
break;
case ".png":
contentType = "image/png";
break;
default:
throw new NotSupportedException("Unrecognized image type.");
}
if (!File.Exists(path))
{
ctx.Response.Status = "Image not found";
ctx.Response.StatusCode = 404;
}
else
{
ctx.Response.StatusCode = 200;
ctx.Response.ContentType = contentType;
ctx.Response.WriteFile(path);
}
}
The above code fails because I want to rewrite the path to a url not a file path. The reason I want to rewrite is because the actual image files is on another server and is not accessible via UNC paths. What am I doing wrong, and is it possible at all to accomplish this?
Cheers
When you are on the call for this handler – then you do not have any more the ability to rewrite your path as I see that you try to do.
The rewrite path is to say to IIS and asp.net that a call for example to
http://www.url.com/one/page1.aspxis served by thehttp://www.url.com/someotherpage.aspx?id=oneYou are all ready not on the final processing of your data, there you must read the file and send it to the browser, for example as: