Friday, November 9, 2012

Deploying an ASP.NET HttpHandler to SharePoint 2010

 How to deploy an HttpHandler to SharePoint 2010 that uses code-behind.  The answer is that you don’t really use code-behind like you would in an ASP.NET application where the code and assembly are in the same folder.  With SharePoint, you need to deploy your code to the Global Assembly Cache (GAC).
You can create the code for an HttpHandler very easily in Visual Studio.  I am going to steal borrow some code from Ted Pattison’s walkthrough, “Creating a Custom HttpHandler in Windows SharePoint Services 3.0” on MSDN (includes a video as well).

using System;
using System.Web;
using Microsoft.SharePoint;

namespace ASHXHandlerDemo
    public class HelloHttpHandler : IHttpHandler
        public bool IsReusable
            get { return false; }
        public void ProcessRequest(HttpContext context)
            SPSite siteColl = SPContext.Current.Site;
            SPWeb site = SPContext.Current.Web;
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello HttpHandler from the site " +
                                   site.Title +
                                   " at " +
The question is how to call that code?  When an HTTP request comes in, how do you map that request to this code? 
The easiest way is to create a .ASHX file and deploy it to the LAYOUTS directory in the SharePoint root (aka “14 hive”).  To do this, right-click your SharePoint project in Visual Studio 2010 and choose “Add SharePoint Layouts Mapped Folder”. 
In that newly created folder, add a new file with a .ASHX extension with the following contents.  The .ASHX file just points to the code in the GAC using the fully-qualified assembly name.

<%@ Assembly Name="Microsoft.SharePoint, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Assembly Name="ASHXHandlerDemo, Version=, Culture=neutral, PublicKeyToken=684a624f7b7a49ae" %>
<%@ WebHandler Language="C#"  Class="ASHXHandlerDemo.HelloHttpHandler" %>
The solution looks like this in Visual Studio 2010.
When you build and deploy your solution from Visual Studio, the code is compiled into an assembly (a .DLL) and registered in the Global Assembly Cache.  The output is:

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from .Net Core Training in Chennai. or learn thru .Net Core Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Es6 Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.