I want to make an ajax call from jQuery to my server. Basically, I want the request to be sent as a POST with a content-type of x-www-form-urlencoded and the corresponding parameters (parameter1=X¶mter2=Y¶meter3=Z). I want the response to be JSON.
The server environment is .NET. I have been experimenting with the three methods below, but have not been able to get one to work quite right.
ASPX – Using an aspx to process and return JSON, I can get it to work, but I need to serialize the JSON myself. This is possible, but I was hoping for something more convenient. Also, correct me if I’m wrong, but I would imagine that aspx pages have a lot of extra overhead involved since they are expected to do more than just execute a method and return simple JSON.
ASMX and WCF – With asmx and WCF, I can get it to return JSON, but only if I send JSON in the request.
What is the best server side “framework” to use for this request / response type? .aspx, .asmx, or WCF? Since I have been able to at least get aspx to work for this, is that even an appropriate approach?
I’ve seen other products out there that expose an API via a web service and use a name / value querystring request format with a JSON response type, but this seems to be a difficult feat to accomplish in .NET.
You’re right that ASPX pages bring extra overhead. Even if you’re not using the WebForms framework at all, requests to ASPX pages still must filter through the entire page lifecycle.
If you prefer that sort of low-level approach, reading QueryString parameters and responding with manually serialized JSON, an ASHX HttpHandler would probably be the best solution.
Personally, I prefer ASMX services. Sending JSON parameters in isn’t very difficult (and you’ll probably end up doing that anyway once you begin sending nested objects or collections, which is a mess via simple key/value pairs), and it’s nice to avoid the needless ceremony of deserializing and serializing during every request.
People will tell you WCF is the correct solution since it’s newer, but .NET 4’s WCF isn’t currently a great fit when you’re using jQuery. It’s not as flexible when dealing with DateTime and Enum types, and it has unwieldy Dictionary serialization. WCF’s new WCF Web Api solves those problems though if you want to try something a bit ahead of the curve.