We had a situtation recently where we needed to allow users to download a pdf file from our server but we did not want to show the URL in the browser window. Although there are many ways to do this we opted to use an aspx page to retrieve the file and present it to the user. Knowing we will probably use this method againe in the application we decided to make sure the page was reusable.
The code below is of a webform load event. There are two querystring parameters, obviously these parameters are relevant to our requirements and you may user different parameters. The t parameter is the token, which is passed to the backend server as an identifier e.g. eventid, certificateid or something similar. The r parameter is to identify which url should be called.
protected void Page_Load(object o, EventArgs e) { var token = Request.QueryString["t"]; var report = Request.QueryString["r"]; var URL = string.Empty; switch (report.ToLower()) { case "u1": URL = System.Configuration.ConfigurationManager.AppSettings["url1"]; break; case "u2": URL = System.Configuration.ConfigurationManager.AppSettings["url2"]; break; } var fullURL = string.Format("{0}{1}", URL, token); var client = new System.Net.WebClient(); try { Byte[] buffer = client.DownloadData(fullURL); if (buffer != null) { Response.ContentType = "application/pdf"; Response.AddHeader("content-length", buffer.Length.ToString()); Response.BinaryWrite(buffer); } } catch (System.Net.WebException ex) { if (((System.Net.HttpWebResponse)ex.Response).StatusCode == System.Net.HttpStatusCode.NotFound) { Server.Transfer("/404.aspx", false); } } }
For us this page was called pdf.aspx, possible URLs this page will be called with are;
http://www.somedomain.com/pdf.aspx?t=1234&r=u1 http://www.somedomain.com/pdf.aspx?t=RY6N-UX6M&r=u2
It is possible to leave the token parameter blank if an identifier is not needed.
http://www.somedomain.com/pdf.aspx?t=&r=u2
The URLs of the backend server are stored in the web.config appSetting section, possible examples are.
<appSettings> <add key="url1" value="http://somebackendserver/{0}" /> <add key="url2" value="http://anotherserver.addomain.net/certificates.aspx?ref={0}" /> </appSettings>
I have replaced the actual appSettings used with url1 and url2, your appSettings will have meaningful names.
The pdf file is downloaded to a byte array and presented to the user. If a WebException occurs the status of the response is checked and if a HttpStatusCode.NotFound status was returned from the backend server the applications 404 page is displayed.
There are a number of ways to extend this code and functionality relevant to any purpose.
You must be logged in to post a comment.