Figure 1. Add Generic handler via Application page template

Generic handlers have an extension .ASHX. It's a good solution to render documents or images for user on server-side after user requests, not web page. Generic Handlers solution (.ashx files) are not directly supported by Visual Studio 2010 for SharePoint projects. But there's a little trick for this.

1. In your SharePoint 2010 Project when you press Add New Item, you won't find item called "Generic Handler". To create "Generic Handler" item in SharePoint 2010, you need to choose "Application Page" template and change extension of filename to ".ashx" (Figure 1)

Figure 1. Add Generic handler via Application page template

Figure 1. Add Generic handler via Application page template

2. Open and edit "SPHandler.ashx"

Remove all the contents and insert code like this according to your namespace:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ WebHandler Language="C#" Class="MyFormSun.SPHandler" %>

 

3. Open and edit SPHandler.ashx.cx, change code of Application page template to generic handler:

Original code:

namespace MyFormSun 
{
    public partial class SPHandler : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
}

 

New code should be like this:

namespace MyFormSun
{
    public partial class SPHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { throw new NotImplementedException(); }
        }

        public void ProcessRequest(HttpContext context)
        {
            //throw new NotImplementedException();
            context.Response.Write("generated by ashx");
        }
    }
}

 

4. Close your Visual studio project, open file "*.csproj" of your project in text editor and add to <PropertyGroup> section this property:

<TokenReplacementFileExtensions>ashx</TokenReplacementFileExtensions>
Figure 2. XML code of .csproj file

Figure 2. XML code of .csproj file

If you don't complete step 4, you'll got the error message after deploying generic handler to SharePoint farm:

Parser Error Message: Could not load file or assembly '$SharePoint.Project.AssemblyFullName$' or one of its dependencies. The system cannot find the file specified.

Figure 3. Potential error in generic handler for SharePoint 2010

Figure 3. Potential error in generic handler for SharePoint 2010

It's a very potential error in generic handler for SharePoint 2010 especially in the first development 🙂