tags:

views:

42

answers:

2

I have a folder with pdfs, but I don't want them to be public (like just typing www.domain.com/pdfs/doc.pdf).

I need them to have a security measure of some sorts (like www.domain.com/loadpdf.asmx?key=23452ADFASD12345 or using POST)

How do I do this?, ive found out how to create a pdf, but not how to load one from server.

thanks.

+1  A: 

You need to use a custom http handler to handle those requests. Here is an article the covers your exact question.

awright18
+1  A: 

Read the PDF into a byte array and use that. As awright18 said, do this in a handler (.ashx). Something like this:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MapHandler : IHttpHandler, IReadOnlySessionState
{

    public void ProcessRequest(HttpContext context) {
        CreateImage(context);
    }

    private void CreateImage(HttpContext context) {

        string documentFullname = // Get full name of the PDF you want to display...

        if (File.Exists(documentFullname)) {

            byte[] buffer;

            using (FileStream fileStream = new FileStream(documentFullname, FileMode.Open, FileAccess.Read, FileShare.Read))
            using (BinaryReader reader = new BinaryReader(fileStream)) {
                buffer = reader.ReadBytes((int)reader.BaseStream.Length);
            }

            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("Content-Length", buffer.Length.ToString());
            context.Response.BinaryWrite(buffer);
            context.Response.End();

        } else {
            context.Response.Write("Unable to find the document you requested.");
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

I found this thread here at SO useful, but the above should work for you.

Jay Riggs
cool thank you, just one question, will this preserve the filename if the user chooses to save the file?
sergiogx
Glad to help. No, it doesn't preserve the filename. It appears that the class name of the handler is the default filename. I plan to see if I can change the default filename to something more meaningful. If you find a way to do this (or if someone out there knows) please post!
Jay Riggs