views:

163

answers:

2

I'm using .NET 2.0 and Visual Studio 2005 to try to create a web service that can be consumed both as SOAP/XML and JSON. I read Dave Ward's Answer to the question How to return JSON from a 2.0 asmx web service (in addition to reading other articles at Encosia.com), but I can't figure out how I need to set up the code of my asmx file in order to work with JSON using jQuery.

Two Questions:

  • How do I enable JSON in my .NET 2.0 ASMX file?
  • What's a simple jQuery call that could consume the service using JSON?

Also, I notice that since I'm using .NET 2.0, I i'm not able to implement using System.Web.Script.Services.ScriptService.


Here's my C# code for the demo ASMX service:

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;


/// <summary>
/// Summary description for StockQuote
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class StockQuote : System.Web.Services.WebService {

    public StockQuote () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 

    }

    [WebMethod]
    public decimal GetStockQuote(string ticker)
    {
        //perform database lookup here
        return 8;
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }        
}

Here's a snippet of jQuery I found on the internet and tried to modify:

    $(document).ready(function(){
        $("#btnSubmit").click(function(event){
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "http://bmccorm-xp/WebServices/HelloWorld.asmx",
                data: "",
                dataType: "json"
            })
            event.preventDefault();
        });
    });
+3  A: 

You can use ScriptService with .NET 2.0 / Visual Studio 2005. You just need to install the ASP.NET AJAX Extensions that were released before .NET 3.5, before it became a core component of the framework.

Aaronaught
@Aaronaught I saw that in Dave Ward's answer (referenced in my Q) and installed it, but how do I get added to my project? For example, if I go to "Add Reference" and look in .NET components, I don't see `System.Web.Script`. Is there another name for what I need to include in the older AJAX extensions?
Ben McCormack
+1 for schooling me again. I haven't used vs05 since vs08 beta.
Sky Sanders
@Aaronaught I think I figured out a few things...the DLL is System.Web.Extensions. You also have to add the project "Ajax Enabled Website" or something like that. I may write up an additional answer with what I've found. Thanks for your help, though.
Ben McCormack
@Ben: Yes, that's correct. I didn't realize it was confusion over the assembly name. I deleted the previous comment, it was incorrect, it still gets installed into the GAC.
Aaronaught
+1  A: 

Getting this to work with Visual Studio 2005 and .NET 2.0 can be a little tricky, especially since a lot of the information on the internet references .NET 3.5, which included the AJAX components by default. As Aaonaught mentioned, you'll first need to install the ASP.NET AJAX Extensions for .NET 2.0.

After the AJAX extensions are installed, you'll want to add a new "AJAX Enabled" website: Go to File > New > Web Site. Choose "ASP.NET AJAX Enabled Website." This will have a different config file than the regular ASP.NET site in .NET 2.0, so it's important to choose this kind of site.

Next, if it's not already referenced in your web config, you'll need to right-click on your project and go to "Add Reference." Add a reference to System.Web.Extensions version 1.0.61025.0. This is where the new scripting libraries live (UPDATE: I can confirm that if you set up a project in VS 2005 as an "AJAX Enabled Web Site", it will automatically include a reference to this assembly in teh Web.Config file).

The last two steps will allow you to add a reference to System.Web.Script.Services.ScriptService in your code. Now you can add an .asmx web service to your project and all you need to do is add the following attribute before your service class: [System.Web.Script.Services.ScriptService]. Your code should look similar to this:

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;



/// <summary>
/// Summary description for StockQuote
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class StockQuote : System.Web.Services.WebService {

    public StockQuote () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 

    }

    [WebMethod]
    public decimal GetStockQuote(string ticker)
    {
        //perform database lookup here
        return 8;
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

}

Part of your problem with your example code is that you didn't call the same web service that you had defined in your example. You had called HelloWorld.asmx from jQuery, but you should have called StockQuote.asmx/HelloWorld. Now when you call your jQuery method using application/json as the content type, the webservice will obey and respond with JSON instead of XML.


JSON POST

POST http://bmccorm-xp/WebServicesAjax/StockQuote.asmx/HelloWorld HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-us
Referer: http://bmccorm-xp/WebServicesAjax/TestJSON.html
Accept: application/json, text/javascript, */*
Content-Type: application/json; charset=utf-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.0.3705; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Host: bmccorm-xp
Content-Length: 0
Connection: Keep-Alive
Pragma: no-cache

JSON Response:

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.1
Date: Tue, 27 Apr 2010 19:11:40 GMT
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Cache-Control: private, max-age=0
Content-Type: application/json; charset=utf-8
Content-Length: 13

"Hello World"

jQuery POST, asking for XML:

POST http://bmccorm-xp/WebServicesAjax/StockQuote.asmx/HelloWorld HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-us
Referer: http://bmccorm-xp/WebServicesAjax/TestJSON.html
Accept: application/json, text/javascript, */*
Content-Type: text/xml; charset=utf-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.0.3705; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Host: bmccorm-xp
Content-Length: 0
Connection: Keep-Alive
Pragma: no-cache

XML Response:

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.1
Date: Tue, 27 Apr 2010 18:54:55 GMT
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Content-Length: 96

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/"&gt;Hello World</string>
Ben McCormack