Create a Simple and Quick Web Service Handler
Nov
25
Written by:
11/25/2009
There are some cases where a full-blown web service or WCF implementation is just too much for the project you’re working on. In those times, I often resort to building a similar implementation using an ASP.Net handler to accepts posts, and return data, just like a standard web service would do. This is not new. We’ve been doing similar things in Classic ASP and PHP for some time now.
I like doing this, because it’s quick, easy, and usually does the job better than a full-fledged web service when this solution fits the project requirements. Otherwise, this is just stupid! ;)
For my example, I am going to assume you need a handler or web service to return JSON data for an AJAX request, much like you’d need for a jQuery AJAX call.
In its simplest form, JSON data that is returned as a result of an AJAX request looks something like the example below. The collection name and values will vary from application to application. Keeping this example in mind, all you have to do is return a string object to the requesting application.
{ collectionName: ['value1', 'value2', 'value3', 'value4', 'value5'] }
First thing is first, add a handler to your project.
When you add the handler, the HTML markup should be relatively empty. That is because all of the action happens behind the scenes, in the code. By default, you will have a class that looks something like this:
This is a great template to start with for what we’re going to do. Now, we simply need to add our own logic to return our data. The format of the data is normally either defined by you, or by the application you’re using or extending.
We are going to assume that we are using an AJAX application that expects to receive a collection of names. We want our resulting JSON data to look like this:
{ fullNames: ['John Dough','Jane Dough','Bart Simpson','Jon Arbuckle','Danger Mouse'] }
First, remove this line of code from your class:
context.Response.Write("Hello World!")
Now, whatever we do with our business logic, we are going to return our JSON string using the context.Response.Write() method.
At this point, we’d already have a Data Source in mind to grab our string-based data. It doesn’t matter where it comes from. I can be from another web service, database, XML files, etc. It doesn’t matter. All you need to do is feed your data into a string builder of some kind, and return it.
Here is my example, using a Customer object that gets populated from an imaginary Data Source.
Dim ctlCustomer As New CustomerController
' grab a list of all of the customer
Dim lstCustomer As List(Of CustomerInfo) = ctlCustomer.GetSortedCustomers()
Dim sb As New StringBuilder
sb.Append("{ fullNames:[")
' Loop through the available customers
For Each person As CustomerInfo In lstCustomer.Values
If Not String.IsNullOrEmpty(person.FullName) Then
' We need to replace the forward slash and single quotes, or the JavaScript will choke on them.
sb.AppendFormat("'{0}',", Regex.Replace(person.FullName, "([/'])", "\$0"))
End If
Next
sb.Append("] }")
If sb.Length > 0 Then
context.Response.Write(sb.ToString)
Else
context.Response.Write(String.Empty)
End If
In our code snippet, we are using a StringBuilder to create the string output that we’re looking for, using the List object that we loaded from our Data Source. We simply loop through the collection, adding the customer to the list of full names. Once the customers are iterated through, the handler writes the resulting string as the response.
Now that we have that logic, our class should look something like this:
Imports System.Web
Imports System.Web.Services
Public Class Handler1
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
Dim ctlCustomer As New CustomerController
' grab a list of all of the customer
Dim lstCustomer As List(Of CustomerInfo) = ctlCustomer.GetSortedCustomers()
Dim sb As New StringBuilder
sb.Append("{ fullNames:[")
' Loop through the available customers
For Each person As CustomerInfo In lstCustomer.Values
If Not String.IsNullOrEmpty(person.FullName) Then
' We need to replace the forward slash and single quotes, or the JavaScript will choke on them.
sb.AppendFormat("'{0}',", Regex.Replace(person.FullName, "([/'])", "\$0"))
End If
Next
sb.Append("] }")
If sb.Length > 0 Then
context.Response.Write(sb.ToString)
Else
context.Response.Write(String.Empty)
End If
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
That’s all there is to it! Our resulting response will look exactly like what our AJAX project asked for. Really simple, right?
2 comment(s) so far...
Re: Create a Simple and Quick Web Service Handler
Nice example Will. Handlers are a convenient option at times. Have you tried the JSON.NET library (james.newtonking.com/projects/json-net.aspx)? It makes dealing with JSON from the server side even easier.
By Shawn Duggan on
11/19/2009
|
Re: Create a Simple and Quick Web Service Handler
Great tip! I have not heard of that tool. Thanks!
By Will on
11/19/2009
|