Tuesday, March 31, 2015

Adding And Deploying Generic Handlers (.Ashx) To A SharePoint 2013 Visual Studio Project

If you try to Add New Item… and select the Web or SharePoint categories in a VS 2010 SharePoint project, you won’t find Generic Handler anywhere.

  • Right-click the project, and select Add New Item…
  • Choose the Application Page template.
  • In the name box, enter a name for your file, with an .ashx extension.
Open the .ashx file, delete the contents and replace with the following, changing your Class=attribute with your desired namespace and class name:

  • Open the ashx.cs file.
    • Add a using statement for System.Web.
    • You probably don’t need the using statement for Microsoft.SharePoint.WebControls, so remove it.
    • Change your namespace if necessary.
    • Change the class to inherit from IHttpHandler.
    • Implement the IHttpHandler interface. Your code should now look something like this:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      using Microsoft.SharePoint;
      using System.Web;
       
      namespace MyNamespace
      {
          public partial class MyGenericHandler : IHttpHandler
          {
              #region IHttpHandler Members
       
              public bool IsReusable
              {
                  get { throw new NotImplementedException(); }
              }
       
              public void ProcessRequest(HttpContext context)
              {
                  throw new NotImplementedException();
              }
       
              #endregion
          }
      }
  • In the Solution Explorer, delete the ashx.designer.cs file, it is not needed.
  • 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.
  • Make sure to enable Token replacement for .ashx extensions. This will replace the$SharePoint.Project.AssemblyFullName$ token with the full strong name of your assembly, enabling you to reference other classes in your compiled assembly from the ashx code-behind.You can read more about token replacement here. To enable this for your Project, Unload your Project, Edit the .csproj file and add the following text to a PropertyGroup, and Reload your project:
    1
    2
    3
    <PropertyGroup>
    <TokenReplacementFileExtensions>ashx</TokenReplacementFileExtensions>
    </PropertyGroup>

No comments:

Post a Comment