Create Custom Http Handler in SharePoint

I would like to share my experience in Creating Custom Http Handler in SharePoint. There are couple of ways to create Http Handler project, but I prefer to use Ashx Handler template from CKSDev Development Tools for SharePoint. It is an easier way to start your Http Handler project and to deploy the solution.

 

CKSDev installation issue

You have to download and install the tool based on your Visual Studio version, so make sure you’re downloading the right version. The other thing that I would like to mention is when I add new item “Ashx handler”, there is a pop up error message look like:

Could not load file or assembly ‘file:///C:\USERS\XXX\APPDATA\LOCAL\MICROSOFT\VISUALSTUDIO\12.0\EXTENSIONS\WCFZLEFI.TYX\CKS.Dev12.Cmd.Imp.v4.dll’
or one of its dependencies.
This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Solution to this is to copy all CKS dll into Global Assembly Cache using gacutil command in Visual Studio command prompt. If you don’t face the issue, then probably they have already fixed it.

 

Pre-Requisite

  • CKSDev Tools for SharePoint installed
  • List “MyList” exists in Root Web

 

Implementation 

So without further ado, lets start create one.

1. Create SharePoint Empty Project, called it CustomHttpHandler and Click OK.
CustomHttpHandler1
2. Enter your Site URL and Deploy it as farm solution and Click Finish.
3. Right Click CustomHttpHandler project > Add > New Item, then Select SharePoint 2013 – Ashx handler (CKSDev) template, called it MyAshxHandler and Click Add.
CustomHttpHandler2
4. Now, the solution explorer will look like below and Set the Build Action of MyAshxHandler.ashx to Content.
CustomHttpHandler4
5. Include MyAshxHandler module in the CustomHttpHandler Feature.
CustomHttpHandler4
6. Update MyAshxHandler.ashx.cs code to below:
using System;
using System.Web;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using System.Linq;

namespace CustomHttpHandler
{
    [Guid("6aa41c89-943a-4242-824b-85c2f433ede3")]
    public partial class MyAshxHandler : IHttpHandler
    {
        private const string ParameterName = "Title";
        private const string ColumnName = "Title";
        #region IHttpHandler Members

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
        /// </returns>
        public bool IsReusable
        {
            get { return false; }
        }

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                context.Response.Clear();

                // Get Title parameter
                string title = GetParameters(ParameterName);
                if(title != string.Empty)
                {
                    Guid siteId = SPContext.Current.Site.ID;

                    // Elevate permission for Anonymous
                    SPSecurity.RunWithElevatedPrivileges(delegate
                    {
                        using (SPWeb web = new SPSite(siteId).OpenWeb())
                        {
                            // Get List
                            SPList myList = web.Lists.Cast<SPList>().Where(lst => lst.Title == "MyList").FirstOrDefault();
                            if (myList == null)
                                throw new Exception("Bad Request, My list is NOT found ...");

                            // Get List item
                            SPListItem myItem = myList.Items.Cast<SPListItem>().Where(strslt => strslt[ColumnName].ToString() == title).FirstOrDefault();

                            // Add / Update Item
                            web.AllowUnsafeUpdates = true;

                            // If new item
                            if (myItem == null)
                                myItem = myList.Items.Add();

                            myItem[ColumnName] = title;
                            myItem.Update();

                            web.AllowUnsafeUpdates = false;

                            // Set the response
                            context.Response.StatusCode = 200;
                            context.Response.StatusDescription = "Successful";
                            context.Response.ContentType = "text/plain";
                            context.Response.Write(String.Format("Item with GUID:{0} and Title:{1} has been created / updated", myItem.ID.ToString(), myItem[ColumnName].ToString()));
                        }
                    });
                }
            }
            catch(Exception ex)
            {
                context.Response.Clear();
                context.Response.StatusCode = 400;
                context.Response.StatusDescription = ex.Message;
            }
            context.Response.End();
        }
        #endregion

        #region private methods
        private string GetParameters(string queryParam)
        {
            try
            {
                return HttpContext.Current.Request.QueryString[queryParam];
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
        #endregion
    }
}
7. Build and Deploy the solution.

 

Results

CustomHttpHandler5

CustomHttpHandler6

 

References

Advertisements

Tagged: , , , , , , , , , , , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: