Click here to Skip to main content
12,813,787 members (31,486 online)
Rate this:
Please Sign up or sign in to vote.
See more: ASP.NET web.Config
Hello everyone

I want to implement Httphandler to secure my documents in my website configured in iis 8.0 windows 8. So that no one can download the files without signing in the website. So in my Httphandler i check that if the session exist or not, if the session exit then allow the user to download the file otherwise redirect him to the login page.

The settings in my config file are as under.

      <add name="Files" type="SecureFileHandler.FileHandler" verb="*" path="*.pdf" />

My HttpHandler is as under

using System;
using System.Web;
using System.Web.SessionState;

    public class FileHandler : IHttpHandler, IReadOnlySessionState

        public bool IsReusable
            get { return true; }

        public void ProcessRequest(HttpContext context)
            if (CheckWetherTheRequestForFileExistOrNot(context))

                if (CheckUsersForFileDownloading(context))

        public bool CheckWetherTheRequestForFileExistOrNot(HttpContext context)

            string url = context.Request.RawUrl.ToLower().Trim();
            if (url.Contains(".pdf"))
                return true;
                return false;

        public bool CheckUsersForFileDownloading(HttpContext context)
            return (context.Session["FrontHiddenID"] == null) && (context.Session["HiddenID"] == null);


It is not working, neither it redirects nor it downloads the file.

Any advice and help regarding this issue is higly appreciated

Posted 15-Jan-13 8:50am
Updated 15-Jan-13 9:29am
ryanb31 15-Jan-13 14:23pm
Where does it give that error? Also, you could just use Forms Authentication.
TanzeelurRehman 15-Jan-13 14:25pm
Thank you for your response
Does forms authentication secure my files too
Gittu Dash 15-Jan-13 15:20pm
See what result you are trying to achieve could be easily achieved using Forms Authentication.
Just make an Extra folder, name it as per your conveyance & implement Forms Authentication for this folder.

If you know forms authentication, you could easily do it.
But if you don't know how exactly to do it, then let me know & I'll post the Process Step wise here as a Solution.
TanzeelurRehman 16-Jan-13 1:13am
I have two type of users one is for front end and one for the admin end, In this httphandler i have to check both of them, if one of the session exist (front end user or admin user)then allow him to download the file otherwise redirect him to login page. Can we implement this scenario in form authentication, (e,g The form authentication should allow if any of the user either front or admin exist. otherwise redirect it to login page) if so pleas guide me.
Gittu Dash 16-Jan-13 4:33am
Yes Forms Authentication surely can do what you want.
Basically you want to allow Downloading to the the users who are logged in to your site, it might be normal user/admin.

So basically to download PDF files every user need to Log In.
So for this As I said Create a Folder & Place all your PDF files in this folder.
Add a web.config to this folder & write code for authorization in it.

Now whenever an user logging in to your site store his identity in a Session variable & whenever any user wants to Download that PDF file check for the Session variable & if present then allow the user to download the file, if not redirect him to login page.

Basically redirecting to login page will be done by Form Authentication.You just need to check if Session Expired or not.

I know it looks like a bit complected, but believe me it's quiet easy to implement.

Let me know if you got it or not.
TanzeelurRehman 16-Jan-13 4:59am
Thank you
I have all my documnets in a folder named doc, I have two type of sessions to be checked one is Session["FrontHiddenID"] and the other is Session["HiddenID"]. If one of the session exist then allow him to download otherwise redirect to login page. If you have time then please submit me some code, i will be very grateful
Gittu Dash 16-Jan-13 5:09am
Just Code Behind logic will be enough or you want right from the Starting of Authorization ?
TanzeelurRehman 16-Jan-13 5:21am
If you can manage from start then it will be your kindness sir
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Your Handler is not right.

First, you will need to set the content header of the file to allow recognition of its mime type.

You could do something like the following (if you had forms authentication):

 public void ProcessRequest(HttpContext context)
if (context.User.Identity.IsAuthenticated)
      string filename = context.Request.QueryString["File"];
      //Validate the file name and make sure it is one that the user may access
      context.Response.Buffer = true;
      context.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
      context.Response.ContentType = "octet/stream";

// or "application/pdf"

      context.Response.WriteFile("~/App_Data/" + filename);
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Is your handler supposed to redirect when FrontHiddenID and HiddenID are null? If so I think you are succeeding there. If not, one of those two fields might have a value which would fail your check.

Also, your handler doesn't actually send the pdf to the user. If you don't have that in code somewhere else, you will need to add the download code here. Here is an example of how to enable downloading of a file.[^]
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

As Per Your Request, Here I'm posting the whole thing right from the Starting of adding Web.config.

Step-1: Place a 'login.aspx' form in your Application & Write the Following code in it under Sign In button:
protected void Button1_Click(object sender, EventArgs e)
    //Write your Logic for validating user as per your requirement.

    //Here I'm Defining a Session Variable for HiddenID Session.
    //You can define FrontHiddenID Session also as per your conveyance
    Session["HiddenID"] = true;

Step-2: Now I'm going to check whether Session variable exists or not when user is clicking Download Link. Here I'm using a Button for implementing Download logic:
protected void Button1_Click(object sender, EventArgs e)
    //Checking if Session variable available or not
    if (Session["HiddenID"] != null || Session["FrontHiddenID"] != null)
        //Mention the Filename user want to Download here
        string fileName = <provide your filename here>;
        //Logic for Providing download link to user 
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
        Response.TransmitFile(Server.MapPath("~/Doc/" + fileName));
    //If Session variable isn't available then Redirecting the user to login page

I guess this should work for you.
Checked in my System & Works fine for me.

Let me know if it's working for you or not.
TanzeelurRehman 17-Jan-13 0:02am
Thank you for your great time,
Stay Blessed

Gittu Dash 17-Jan-13 1:04am
No Probs Dear.
Actually I found this technique is more easier than Authorization, so Provided you with this.

Authorization way is also available, but this'd be easier to implement.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170308.1 | Last Updated 16 Jan 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100