Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Using a Custom HttpHandler by Dan Wahlin
Getting Data in and out of ASP.NET Applications using Ajax and jQuery – Using a Custom HttpHandler by Dan Wahlin
In my previous post I discussed how ASP.NET MVC controllers could be used to serve up JSON data to applications. Examples of additional technologies that can be used are shown next:
1. ASP.NET Web Services (.asmx)
2. Windows Communication Foundation
3. ASP.NET MVC Controller/Action
4. Custom HttpHandler
5. Web API
With ASP.NET MVC you can use a controller action to serve up JSON easily by using the built-in Json() method. An example of a JSON-enabled controller action is shown next:
1 2 3 4 5 | public ActionResult GetQuote(string symbol) { return Json(_SecurityRepository.GetSecurity(symbol), JsonRequestBehavior.AllowGet); } |
In this post I'll discuss how ASP.NET HttpHandlers can be used to serve up JSON data to Ajax clients.
Creating an ASP.NET HttpHandler
Regular ASP.NET pages are a special type of object referred to as an HttpHandler. As users hit a page the handler is invoked and used to serve data to the browser. In cases where JSON data needs to be served to Ajax-enabled clients, a simple HttpHandler can be created and used without much effort on your part. The handler has an .ashx extension and can be hit directly in the browser or called from an Ajax client.
To add an HttpHandler into an ASP.NET Web Forms project right-click on the project and select Generic Handler from the available items as shown next:
After adding the Generic Handler into the project you'll see the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class JsonHttpHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World"); } public bool IsReusable { get { return false; } } } |
Since JSON data will be served from the HttpHandler the first order of business is to reference the System.Web.Script.Serialization namespace:
using System.Web.Script.Serialization;
This namespace has the JavaScriptSerializer class in it which can be used to convert a Customer type to JSON. Once the namespace is included, the ContentType property needs to be changed to a value of text/json:
context.Response.ContentType = "text/json";
At this point the type of object to serialize to JSON can be created, serialized, and returned. The following code contains the complete ProcessRequest method in the HttpHandler. It's used to serialize a Customer object to JSON and then return the string data using the Response.Write() method.
1 2 3 4 5 6 7 8 9 10 | public void ProcessRequest(HttpContext context) { //simulate getting Customer object var cust = new Customer {ID = 2, Name = "John Doe", City = "Chandler"}; //serialize Customer object to JSON var serializer = new JavaScriptSerializer(); var json = serializer.Serialize(cust); context.Response.ContentType = "text/json"; context.Response.Write(json); } |
To call the custom HttpHandler the following jQuery code can be used:
1 2 3 | $.getJSON('JsonHttpHandler.ashx', null, function (data) { alert(data.Name + ' ' + data.City); }); |
This code uses jQuery's getJSON() function to call the HttpHandler on the serve and process the resulting data in a callback function. If data values need to be passed to the service the null parameter value in getJSON() can be replaced with an object literal containing the parameter(s):
{MyDataKey: MyDataValue}
The server can access the parameter value (or values) using the context variables Request property:
string val = context.Request[“MyDataKey”];
Conclusion
In this post you've seen how an ASP.NET HttpHandler can be used to serve JSON data to an Ajax-enabled client. Although using a custom HttpHandler to serve JSON data isn't my preferred approach given the other options available, it's a simple choice that can be used as needed. In the next post I'll discuss how the new Web API functionality available in .NET 4.5 can be used to serve JSON.
Enjoy!
Dan Wahlin
.NET Developer Instructor
Interface Technical Training
You May Also Like
How to Build in a PSMethod to your PowerShell Code
0 71 0In this video, PowerShell instructor Jason Yoder shows how to add Methods (PSMethod) to your code using free software that’s added into the PSObject. For instructor-led PowerShell courses, see our course schedule. Microsoft Windows PowerShell Training Download the Building Methods PowerShell script</a> used in this video. <# ╔══════════════════════════════════════════════════════════════════════════════╗ ║ ║ ║ Building Methods ║ ╟──────────────────────────────────────────────────────────────────────────────╢ … Continue reading How to Build in a PSMethod to your PowerShell Code
Configuring Windows Mobility Center and How to Turn it On and Off
1 1434 1Video transcription Steve Fullmer: In our Windows training courses, we often share information about the Windows 8.1 Mobility Center. Mobility Center was introduced for mobile and laptop devices in Windows 7. It’s present and somewhat enhanced in Windows 8. Since we don’t have mobile devices in our classrooms, I decided to take a little bit … Continue reading Configuring Windows Mobility Center and How to Turn it On and Off
How to use AWS CloudFormation templates to automate solutions inside Amazon AWS
0 380 0In the AWS Class here at Interface, we actually build fully automated solutions with AWS CloudFormations. Here’s an overview of using AWS templates using CloudFormation. CloudFormation is basically an “infrastructure-as-code tool” where you can go into a declarative document and define all the resources that you want and feed the document into the CloudFormation … Continue reading How to use AWS CloudFormation templates to automate solutions inside Amazon AWS
Pingback: How to add Help Pages to ASP.NET Web API Services – Dan Wahlin | Interface Technical Training