C# .NET - Restrict the user from direct access of my images and PDFs through URL

Asked By Dinesh Pathak on 11-Apr-13 06:43 AM
By using the handlers i am able to restrict the anonymous user from access of images through direct URL but i am not able to access the images within application afterlogin .
 
I want to restrict the user from direct access of my images and PDFs through URL(Like www.test.com/userimage.image1.jpg)
 
so please tell me what should i do to replicate this issue.
Robbe Morris replied to Dinesh Pathak on 11-Apr-13 08:59 AM
Rather than exposing the direct url to the image in your image tag, you expose an http handler (.ashx file).

The code behind in the .ashx file would check for the referrer and make sure it is valid.  A direct call to the .ashx from outside the browser would have a referrer of null or empty string.  You'd use Response.WriteFile to write the contents of the image to the output stream.

context.Response.StatusCode = 200;

context.Response.ContentType = contentType;

context.Response.WriteFile(fileName);