Recently I came across a situation where I was using aspx page to return Json Data to bind a flex . It was going well (mostly all the times ) except a situation (Probality with 1 out of 10 ) where I was getting redundent JSON data from aspx page .
Then I got a suggestion to try with HttpHandlers to get the JSON data instead of using aspx page .
I tried both the ways & conclusion was like this :
Trying aspx page to return JSON data :
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(); } }
In this case , you need to Clear out the Buffers , then play with cache , then Flush the response buffer and finally complete the request .
Now , Trying HttpHandler to return JSON data : } 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); }
Conclusion :
As we have undoubtedly concluded, there’s a lot of overhead associated with returning JSON data from an ASPX file.
If you consider the alternative, an HTTPHandler,there is a cleaner, best-practices approach which provides the same outcome with less code, comments and risk.
So , it is always better to use httpHandler in this scenerio .
Other problem I faced in this approach was to get the session Object in httphandler class . The Solution Is given Here :
All we need to inherit the class from IRequiresSessionState . The Example Is given below(Considering Class name as AutoComplete) :
public class AutoComplete : IHttpHandler, IRequiresSessionState { ——————– ——————–
}