One of the more popular posts on this blog detailed how to create and deploy a Generic ASHX handler with your SharePoint projects. While you can still do this manually per that post, this is made much easier with the inclusion of a new item template that is part of the CKSDev tools extension.
Since this particular change set and version 2.3 of CKSDEV, there is now an ASHX item template that you can use to create and deploy generic ASHX handlers to your SharePoint farms. Generic handlers are a lightweight and quick way to “roll your own” SharePoint web services layer, and I’ve used them quite a bit. Especially in AJAX anonymous access scenarios (where the Lists.asmx services will not work), generic handlers can be easily deployed to the LAYOUTS or ISAPI virtual directories and act as a nice shim/proxy to provide data to client-side callers.
To add a handler to your project, first install the CKSDEV tools. Then right-click a SharePoint project in the Solution Explorer and choose Add > New Item…
Once you’ve given it a name and clicked Ok, you’ll see two files, one with .ashx extension, and the other code-behind file with .ashx.cs extension.
You shouldn’t have to edit the .ashx file at all, unless you want to reference classes from other SharePoint assemblies in your code behind, like Microsoft.SharePoint.Portal, or Microsoft.Office.Server.UserProfiles, etc., in which case you need to add an @Assembly directive for each of those dlls. There is an @Assembly reference for Microsoft.SharePoint.dll already setup.
Note:As of CKSDEV 2.4, the Item Template doesn’t set the Build Action properly on the .ashx file, so you need to manually set the Build Action to Content yourself.
Once in the code behind, you will see the typical place to add your code in the ProcessRequest method. Some things you get with this approach:
- You don’t have to hard code the name of your assembly in the .ashx file (the SharePoint project replacement tokens are used)
- The ASHX file is deployed to the layouts directory automatically for you (if you change the Build Action to Content)
- You don’t have to edit your .csproj file and include the TokenReplacementFileExtensions entry for .ashx (the item template does this for you)
Special thanks to Wes Hackett for taking my contribution and making it work properly within the CKSDEV framework.