Quick Tip: Creating a Custom SharePoint HttpHandler (ASHX) using Replacement Tokens
I’ve done this a few times recently, thought it would be good to share.
Since 2007 we’ve known that there was a handy little pattern for creating and deploying an HttpHandler within the SharePoint Environment. This same pattern holds in 2010. In this post I’m going to show how to create the httphandler in Visual Studio 2010, and also show you how to wire up the Class attribute in your .ashx file using Visual Studio 2010 replacement tokens.
In Visual Studio 2010 you would go about this by following theses steps:
- Creating an Empty SharePoint Project
- Add an application page to the project, but give it a .ashx extension
- delete the filename.designer.cs file
- delete all the markup from the .aspx page
- remove the generated Page_Load method from filename.cs codebehind
- make sure filename.cs has using statements for “System.Web” and “System.Runtime.Interopservices”
- Inside Visual Studio go to the Tools menu and choose “Create GUID”
- Select “5. [Guid(xxxx-xxx….)]”
- Select Copy and close the Create GUID window
- Now paste that line right above your public class declaration inside of filename.cs
At this point your filename.cs code file should look something like:[Guid("61e934b3-6e24-4da4-93f4-0768fb0c468c")] public class handler : IHttpHandler { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { } }
Note above something that I believe is important: the GUID you have should be converted to lowercase (select it in Visual Studio and hit ctrl+u) - Now the next step is to wire the markup in the .ashx file up to our class that gets built into the Assembly. Open up the .ashx file and paste this single line into the file:
<%@ WebHandler Class="$SharePoint.Type.61e934b3-6e24-4da4-93f4-0768fb0c468c.AssemblyQualifiedName$" %>
Note above that the GUID in the token should match the GUID on your class declaration from step 10. This should have been generated during step 9. -
The last step is to make sure that visual studio pays attention to your .ashx files for token replacement. I could walk you through this step by step but there are clear instruction on MSDN here The final section in that document refers to “Adding Extensions to the Token Replacement File Extensions List “. Follow the steps in that section.
Now you should be all set with token replacements in your .ashx files! If you want to test this, right click your project in Visual Studio and choose “Package”. Navigate in the file system to <Project Directory>\pkg\<Debug|Release>\Project Name\Layouts\<path to ashx file> and open up the .ashx file. You should see the appropriate class/assembly reference!
Hope it helps!