Creating Generic HTTPHandler in SharePoint

HTTP Handlers are components that implement the System.Web.IHttpHandler interface. It writes some data to the server HTTP response. A file ending with .ashx. In SharePoint they are deployed to the _layouts directory. Generic handlers are a lightweight and quickier way then creating a SharePoint web service layer. I have found them especially useful in getting data from server side to the client side as JSON. They are also useful in AJAX anonymous access scenarios when you cannot use SharePoint .asmx services.

In the recent project I’ve been doing at work, we have created a few Generic HTTPHandlers to call search and return the results as JSON. This has allowed us to have a pure AJAX single page application that can call server side code.

Visual Studio Item Templates for Generic Handlers are not directly supported by Visual Studio SharePoint Projects. When you Add New Item… and search for Installed Templates in a SharePoint project, you will not find Generic Handler anywhere. The ASP.NET handler will require extra work for you making entries in the web.config just to get it to work. There are two solutions to get a Generic Handler in SharePoint:

  • Use CKSDev. By Installing CKSDev there will be a built in handler that will work for you. Just select it when Adding a New Item, and then set the Build Action to Content. Once deployed you will find it at location http://<site>/_layouts/<ProjectName>/myhandler.ashx (Make sure that you add the handler to the feature)
  • Without using CKSDev.
    • Add New Item… and add an Application page, but name the extension .ashx.
    • Delete the ashx.designer.cs file.
    • Open the .ashx file, delete the contents, and replace with the following. (Add your own GUID and ensure all letters are lower case).

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>

<%@ WebHandler Class="$SharePoint.Type.be94b0d0-ca37-4783-b8e9-06ba0477a22f.FullName$" %>

  • Open the ashx.cs file.
  • Add the using statement using System.Web
  • Add the using statement using System.Runtime.IntropServices;
  • Change your namespace if you want.
  • Change the class to inherit from IHttpHandler
  • Implement the IHttpHandler interface. (IsReusable and ProcessRequest)
  • Add [Guid(“BE94B0D0-CA37-4783-B8E9-06BA0477A22F”)] (Guid should match the Guid from the ASHX page, except uppercase)
  • In the Solution Explorer, click the .ashx file and in the Properties pane, set the Build Action to Content.
  • In the Solution Explorer, click the .ashx.cs file and in the Properties pane, set the Build Action to Compile.
  • Now we need to Save and Close the solution.
  • Edit the .csproj file and add the following text to a PropertyGroup, and reload your project in Visual Studio.