HTTPHandler with JSON Data

As javascript libraries, particularly jQuery, increase in popularity so do web techniques using AJAX and JSON.

Have you ever seen this code?  It is front and back of an ASPX file with the single responsibility to return JSON data per an AJAX request.

GetDataPage.aspx

<%@ Page Language="C#" AutoEventWireup="true" 
    CodeFile="GetDataPage.aspx.cs" Inherits="GetDataPage" %>
<%-- 
    This minimal code is here to prevent the following error:
     "Using themed css files requires a header control on the page"
     Please see http://www.west-wind.com/WebLog/posts/4662.aspx 
     for more information --%>
<head id="Head1" runat="server" visible="false" />

GetDataPage.aspx.cs

using System;
using System.Web;
using System.Text;

public partial class GetDataPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Clear out the buffer
        Response.ClearHeaders();
        Response.ClearContent();
        Response.Clear();

        // Do not cache response
        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        // Set the content type and encoding for JSON
        Response.ContentType = "application/json";
        Response.ContentEncoding = Encoding.UTF8;

        int page = int.Parse(Request["p"]);
        string results = DataAccess.GetResults(page);

        Response.Write(results);

        // Flush the response buffer
        Response.Flush();

        // Complete the request.  NOTE: Do not use Response.End() here,
        // because it throws a ThreadAbortException, which cannot be caught!
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }
}

You may have noticed there’s a comment for nearly every code block.  At first, one may find the comments redundant and unnecessary, but really they are call for help.  A code:comment ratio like this usually indicates you really need to focus on what’s happening with the code because if you aren’t paying attention, bad things might happen.

As you have undoubtedly concluded, there’s a lot of overhead associated with returning JSON data from an ASPX file.  This statement is especially true if you consider the alternative, an HTTPHandler.  Here’s a cleaner, best-practices approach which provides the same outcome with less code, comments and risk.

GetDataHandler.ashx

<%@ WebHandler Language="C#" Class="GetDataHandler" %>

using System.Text;
using System.Web;

public class GetDataHandler : IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }
    
    public void ProcessRequest (HttpContext context) 
    {
        context.Response.ContentType = "application/json";
        context.Response.ContentEncoding = Encoding.UTF8;

        int page = int.Parse(context.Request["p"]);
        string results = DataAccess.GetResults(page);
        
        context.Response.Write(results);
    }
}

If you are already accustomed to using generic handlers to stream back images, XML, JSON data, etc, this post was probably a bore. But it’s sometimes easy to forget what’s available to imageyou in the vast .NET stack, so hopefully you appreciate the friendly reminder.  In either case, it still surprises me how many examples use the ASPX approach.  In fact, the practice is common enough that I sometimes wonder if there’s an HTTPHandler gotcha to which I’m not privy .  If I am missing something, please let me know.

If you’re still interested, attached you’ll find code which populates two jQuery Flexbox controls using JSON data provided through an ASPX and ASHX files.  This may be worthwhile download if you’re interest in the generic handler code or you want a further look at Flexbox in action after last week’s post.

Download JsonHandler Sample Project: JsonHandler.zip

Comments

  1. Thanks for the post.

    At least there’s one other person is also using the generic handler for ajax requests. I thought I’m the only one.

    I too haven’t picked up any gotchas yet.

    It would be nice though if we had a method of converting IQuerable to Json like in mvc

  2. @Paul Allies – Thanks for the comments. I’m surprised, too, that few seem to use the generic handler — in examples anyway. IQueryable to Json, eh? I’ll stay on the lookout. Thanks.

  3. Ben,
    Is there a benefit of using generic handlers to return JSON instead of using a Webservice with the ScriptService Attribute?

    I’m able to return an array of any object type to a jTemplate. It seems compiling a string of the JSON is opening up more possibilities for typos.

    That being said, I am fairly new to using jQuery, so I’m probably overlooking some plain explanation.

  4. Hi Mike. That’s a great question. I think my sample project may not have represented JSON very well. In most cases, one would simply serialize an object(s) to JSON rather than jumping through hoops building the string like I did in the sample. As long as your objects are serializable, I’m not sure there’s much concern with typos. Of course, your solution is one I hadn’t actually considered and should work perfectly well. I’m really glad to provided an alternative approach. Many thanks.

  5. //1.Test web service.
    [WebMethod(CacheDuration = 30, Description = "This is a testing purpose only for dot net developer.")]
    hello friend,
    i want to communication between device(mobile) and server side, so that our team is decided to work on web service in dot net.
    but the device used json response instead of xml and dot net web service return predefine xml response which is take more time to extract json string from the web service.
    Below code help to read the json response directlly without xml tag.

    Check the below test sample and let me know your comment.
    Thanks
    AshishJ

    //1.Test web service.
    [WebMethod(CacheDuration = 30, Description = "This is a testing purpose only for dot net developer.")]
    public void TestWebServiceJson()
    {
    String sJSonResponce = “{‘GenInfo’:[{'type':'Response', 'appname':'iBehavior'} ],’Registration’:[{ ‘categorylist’:['catid':'value', 'category':'value', 'couponcount':'value']} ]}”;

    Context.Response.ContentType = “text/plain”;
    Context.Response.Write(sJSonResponce);
    }

  6. “At first, one may find the comments redundant and unnecessary, but really they are call for help. A code:comment ratio like this usually indicates you really need to focus on what’s happening with the code because if you aren’t paying attention, bad things might happen.”

    I don’t understand what you are saying here. The comment:code ratio seems fine and completely irrelevant to the topic you are talking about. Nearly every project/company I have worked with has an aim to have a code:comment ratio like this and it IS good practice.

    Please could you clarify what you meant?

  7. Ben,

    Thanks for posting this, very useful article – Great to see ASHX being used for its intended purpose.

    Cheers!
    Simon.

closed