Pankaj Agarwal Pankaj Agarwal - 1 year ago 65
ASP.NET (C#) Question

How can i hide/secure image path?

How can I hide/secure image path in I don't want the user see image path directly.

I have googled with my problem and found the following URL:

On this page it suggests changing the image path like this:

<img ID='ImageControl'
src='ShowImage.axd?Path=<% EncryptString("C:\Images\img.ext", Page) %>'

But if user copy this image src and paste it into their browser with the domain name then it will show image.

Answer Source

It really depends on what you are trying to achieve.

If you're trying to stop people linking to your images from another site, then the best option would be to extend the handler you mentioned in your question to only return an image if the Request.Referrer is your own site.

This means that if they did then try and link to the image via your handler, they'd only see a broken image/no image, they wouldn't be able to request the image directly in their browsers, etc.

You should also probably include some sort of time stamp in the encrypted path, and reject requests that come from too long ago - this will again limit the validity of the links:

<img ID='ImageControl' 
     src='ShowImage.axd?Path=<% EncryptString("C:\Images\img.ext|" + DateTime.Now.ToString(), Page) %>' 

Then in your handler:

Dim pathAndTimeEnc As String = ctx.Request.Params("Path")
Dim pathAndTime As String
Dim path As String
Dim timeStamp As DateTime

pathAndTime = Common.DecryptString(pathAndTimeEnc, ctx)
Dim parts = pathAndTime.Split("|"C)
path = parts(0)
timeStamp = DateTime.Parse(parts(1))

Dim fiveMin As TimeSpan = New TimeStamp(0, 5, 0)
If DateTime.Now.Subtract(timeStamp) < fiveMin Then
  ' Return image.
End If

If you're trying to stop people downloading your images then you're not really going to stop more than the most basic internet user - after all to display the image on your site, you'll need to send a copy of it to the client browser.

However, a couple of possible options to make it harder:

  1. Ensure that the images expire immediately, this means the browser shouldn't keep them locally for that long - however it does mean that none of the images will be cached, and you'll end up with higher bandwidth useage for repeat viewers; if you are using the handler you can do this in code: Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetExpires(DateTime.Now);
  2. Use CSS to place a transparent 1x1px image over the top of the images on your site - this way if a user right-clicks on the image to save it, they will get the path to the transparent image rather than the one they are expecting (Flickr does/used to do this)

At the end of the day, if you put some content online, then it's very hard to stop the most dedicated "thief" from taking it and using it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download