Create Your Own HttpHandler In C#

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 add a class named HandlerClass to it and apply the interface IHttpHandler.

Now, let’s write some code for the ProcessRequest (implemented through the interface) method in this class.

public void ProcessRequest(HttpContext context)
{
    if (context.Session["UserId"] == null)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Please Login to download this file");
    }
    else if (context.Session["UserId"] != null)
    {
        string strURL = context.Request.RawUrl;
        context.Response.ContentType = "text/plain";
        context.Response.Write(strURL);
        // Get the file name
        string strFileName = strURL.Substring(strURL.LastIndexOf("/") + 1);
        string strFilePath = context.Server.MapPath(strFileName);
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.Clear();
        response.AppendHeader("content-disposition", "attachment; filename=" + strFilePath);
        response.ContentType = "application/octet-stream";
        response.WriteFile(strFilePath);
        response.Flush();
        response.End();
    }
}

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.

<httpHandlers>
    <add verb="*" path="*.pdf" type="MyHttpHandler.HandlerClass, MyHttpHandler"/>
    <add verb="*" path="*.zip" type="MyHttpHandler.HandlerClass, MyHttpHandler"/>
    <add verb="*" path="*.rtf" type="MyHttpHandler.HandlerClass, MyHttpHandler"/>
    <add verb="*" path="*.docx" type="MyHttpHandler.HandlerClass, MyHttpHandler"/>
</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 HTTP handler 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.

<handlers>
    <add verb="*" path="*.pdf" type="MyHttpHandler.HandlerClass, MyHandler" name="MyHttpHandler"/>
    <add verb="*" path="*.zip" type="MyHttpHandler.HandlerClass, MyHandler" name="MyHttpHandler"/>
    <add verb="*" path="*.docx" type="MyHttpHandler.HandlerClass, MyHandler" name="MyHttpHandler"/>
    <add verb="*" path="*.rtf" type="MyHttpHandler.HandlerClass, MyHandler" name="MyHttpHandler"/>
</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 in.

The screen is as in the following screenshot.

run program

The code behind this page is the following.

protected void Page_Load(object sender, EventArgs e)
{
    Session["UserId"] = null;
    Session["Password"] = null;
}
protected void btnLogin_Click(object sender, EventArgs e)
{
    Session["UserId"] = txtUserName.Text;
    Session["Password"] = txtPassword.Text;
    Response.Redirect("/Default.aspx");
}

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 files without login, 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 to 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 in, if you try and hit the same url, the file will download successfully.

I hope this article provided you an insight into the implementation of HTTP handler in C#.

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

I hope it helped!


Recommended Free Ebook
Similar Articles