Create Your Own HttpHandler In C#

Here are the steps:

Step 1: Creating Handler Dll.

Let’s create an http handler dll which we will later import into our project.

Create a Class Library Project and add a class named HandlerClass to it and apply the interface IHttpHandler.

Now, let’s write some code for ProcessRequest (implemented through the interface) method in this class.
  1. public void ProcessRequest(HttpContext context)    
  2. {    
  3.     if (context.Session["UserId"] == null)    
  4.     {    
  5.         context.Response.ContentType = "text/plain";    
  6.         context.Response.Write("Please Login to download this file");    
  7.   
  8.     }    
  9.     else if (context.Session["UserId"] != null)    
  10.     {                    
  11.         string strURL = context.Request.RawUrl;    
  12.         context.Response.ContentType = "text/plain";    
  13.         context.Response.Write(strURL);    
  14.         //to get the file name    
  15.         string strFileName = strURL.Substring(strURL.LastIndexOf("/") + 1);    
  16.         string strFilePath = context.Server.MapPath(strFileName);    
  17.         System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;    
  18.         response.Clear();    
  19.         response.AppendHeader("content-disposition""attachment; filename=" + strFilePath);    
  20.         response.ContentType = "application/octet-stream";    
  21.         response.WriteFile(strFilePath);    
  22.         response.Flush();    
  23.         response.End();    
  24.     }    
  25.   
  26. }   
The above method check that the Session["UserId"] is not null.

If the value is null then the user is not allowed to download the file, else the file is downloaded.

Now, build this code and after successful build, create another web project where we would use this dll.

Step 2: Creating Handler Testing Project.

Let's create another WebApplication by the name "TestingHandler", add the Reference of the above project into it.

After that, let's create a folder called files in the project and add certain files to it (pdf, zip, word etc).

I am currently including some random documents for the following formats: pdf, docx, rtf and zip

Now, I would register my http handler in this application and in order to do that, we would write the below code to the web.config file in the application:

The first set of lines would go under the system.web tag and it is as in the following code snippet:
  1. <httpHandlers>    
  2.    <add verb="*" path="*.pdf" type="MyHttpHandler.HandlerClass, MyHttpHandler"/>    
  3.    <add verb="*" path="*.zip" type="MyHttpHandler.HandlerClass, MyHttpHandler"/>    
  4.    <add verb="*" path="*.rtf" type="MyHttpHandler.HandlerClass, MyHttpHandler"/>    
  5.    <add verb="*" path="*.docx" type="MyHttpHandler.HandlerClass, MyHttpHandler"/>    
  6.   
  7.  </httpHandlers>  
The above code depicting the restriction would be applied on the mentioned file formats only and all others would be allowed without any issue.

The httphandler is also registered using the type attribute by using the namespace of the handler and also the class name.

The handler is also mentioned inside the tag system.webServer by using the following mentioned lines:
  1. <handlers>    
  2.   
  3.   <add verb="*" path="*.pdf" type="MyHttpHandler.HandlerClass, MyHandler" name="MyHttpHandler"/>    
  4.   <add verb="*" path="*.zip" type="MyHttpHandler.HandlerClass, MyHandler" name="MyHttpHandler"/>    
  5.   <add verb="*" path="*.docx" type="MyHttpHandler.HandlerClass, MyHandler" name="MyHttpHandler"/>    
  6.   <add verb="*" path="*.rtf" type="MyHttpHandler.HandlerClass, MyHandler" name="MyHttpHandler"/>    
  7.   
  8. </handlers>   
This way, our custom handler is now registered in the application.

Now, let's create a simple login screen and just set the values to the Session object UserId after logging.

The screen is as in the following screenshot:

run program

The code behind this page is the following:
  1. protected void Page_Load(object sender, EventArgs e)    
  2. {    
  3.     Session["UserId"] = null;    
  4.     Session["Password"] = null;    
  5. }    
  6.   
  7. protected void btnLogin_Click(object sender, EventArgs e)    
  8. {    
  9.     Session["UserId"] = txtUserName.Text;    
  10.     Session["Password"] = txtPassword.Text;    
  11.   
  12.     Response.Redirect("/Default.aspx");    
  13. }   
It's a simple code to set values in the Session object UserId.

Now let's run the application.

As per the status of this project, we have to stop the users from downloading file without login and so we would try to download the file using the url of the file location itself. for example, in order to download the personal.pdf file, we use the url http://localhost:20098/Files/Personal.pdf (Please refer the attached project to understand the structure of the file).

We notice that without a proper login, if we hit the above mentioned url then we get the following output:

run
Now, try and download the file after logging in. As there is no specific user described, you can use any username and password. e.g. UserName: admin and Password: admin.

After logging, if you again try and hit the same url, the file will download successfully.

I hope this article provided you an insight on the implementation of httphandler in C#.

Please find the attached code for the handler as well as the testing Web Application.

Hope it helped!

Up Next
    Ebook Download
    View all
    FileInfo in C#
    Read by 9.7k people
    Download Now!
    Learn
    View all