May 22

The 3.5 beta version of the .NET platform lets us use JSON as the serialization format used by a web service call. The best of all is that this means that we can now call a web service from an ASP.NET AJAX page.

To do this, you need to add some entries to your configuration file (on the server side). Getting a proxy on the client side is a simple as adding a service reference through the ScriptManager control. Lets start by seeing the service code (which was generated by adding a new WCF service to an AJAX futures enabled web site):

public interface ITest
    string MyOperation1(string myValue);

public class Test : ITest
    public string MyOperation1(string myValue)
       return “Hello: ” + myValue;

The svc file looks like this:

<%@ ServiceHost Language=”C#” Debug=”true” Service=”Test”
              CodeBehind=”~/App_Code/Test.cs” %>

Now you need to add an endpoint that is able to understand JSON. In my case, I wanted to expose a mex endpoint too, so I ended up with the following definitions for my web service:

  <service name=”Test” behaviorConfiguration=”metadataSupport”>
         <endpoint binding=”webHttpBinding”
          <endpoint address=”mex” binding=”mexHttpBinding” contract=”IMetadataExchange”/>

As you can see, i”m using  a WebHttpBinding and I”m saying that there”s a new jsonBinding element which configures the traditional webHttpBinding that is introduced by default by the WCF framework. In this case, we”re just setting the message encoding to JSON:

        <binding name=”jsonBinding” messageEncoding=”Json”/>

We also need to add a new behavior that looks like this:

     <behavior name=”metadataSupport”>
         <serviceMetadata httpGetEnabled=”true” httpGetUrl=””/>
        <behavior name=”jsonBehavior”>
           <enableWebScript />

And that”s it! the only thing you need to do to call this WCF service from your AJAX ASP.NET page is add a reference to the web service:

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
     <asp:ServiceReference Path=”Test.svc” />

Doing this ends up inserting the following js code in your page:

ITest=function() {
this._timeout = 0;
this._userContext = null;
this._succeeded = null;
this._failed = null;
MyOperation1:function(myValue,succeededCallback, failedCallback, userContext) {
return this._invoke(ITest.get_path(), ”MyOperation1”,false,{myValue:myValue},succeededCallback,failedCallback,userContext); }}
ITest._staticInstance = new ITest();
ITest.set_path = function(value) { ITest._staticInstance._path = value; }
ITest.get_path = function() { return ITest._staticInstance._path; }
ITest.set_timeout = function(value) { ITest._staticInstance._timeout = value; }
ITest.get_timeout = function() { return ITest._staticInstance._timeout; }
ITest.set_defaultUserContext = function(value) { ITest._staticInstance._userContext = value; }
ITest.get_defaultUserContext = function() { return ITest._staticInstance._userContext; }
ITest.set_defaultSucceededCallback = function(value) { ITest._staticInstance._succeeded = value; }
ITest.get_defaultSucceededCallback = function() { return ITest._staticInstance._succeeded; }
ITest.set_defaultFailedCallback = function(value) { ITest._staticInstance._failed = value; }
ITest.get_defaultFailedCallback = function() { return ITest._staticInstance._failed; }
ITest.MyOperation1= function(myValue,onSuccess,onFailed,userContext) {ITest._staticInstance.MyOperation1(myValue,onSuccess,onFailed,userContext); }

which really looks similar to waht you get when you add JSON support to an ASMX web service.

9 comments so far

  1. Jeff Deville
    4:24 am - 5-25-2007

    I was wondering if you could tell me what path to use if I”m hosting the service in an outside application, like a windows service, or console app. There”s no .svc file in this instance, but I thought that putting in the service”s address would work. When I do, I get: “The server method ”[METHOD_NAME]” failed with the following error:… HTTP Error 404…”

    Any suggestions? Thank you.

  2. Luis Abreu
    8:17 am - 5-25-2007

    hello jeff.

    i believe that the same restrictions you had for asmx web services still hold true, ie, you can”t make xdomains calls. if i recall correctly, this happens because, by default, browsers won”t let you use the xmlhttprequest object to perform xdomain calls.

    to solve this, normally we just create a local web service which works as a proxy for the remote service:

  3. Jeff Deville
    5:06 pm - 5-26-2007

    Good to know, thanks Luis.

  4. Gustavo Frederico
    3:28 pm - 7-20-2007

    Eu segui os passos acima e tudo correu bem. Você teria algum exemplo de como usar o serviço afinal? Vejo o código JavaScript gerado, mas não estou certo sobre como utilizá-lo.
    obrigado – Gustavo

  5. luisabreu
    5:31 pm - 7-20-2007

    Claro, sem problema. quando quiseres chamar o servico numa pagina js, basta fazeres algo do genero:

    ITest.MyOperation1( “Luis”, succeddedCallback);

    function succeededCallback(res){
    //res tem o objecto retornado do servidor

  6. luisabreu
    5:31 pm - 7-20-2007

    Claro, sem problema. quando quiseres chamar o servico numa pagina js, basta fazeres algo do genero:

    ITest.MyOperation1( “Luis”, succeddedCallback);

    function succeededCallback(res){
    //res tem o objecto retornado do servidor

  7. xx
    5:29 pm - 9-29-2007

    I get the following error Unrecognized attribute ”messageEncoding”

  8. Suneel
    7:58 am - 7-21-2008

    I am also getting the same error Unrecognized attribute ”messageEncoding”. Any update on this.

  9. ChristiWarner29
    10:18 pm - 11-25-2010

    I think that to get the personal loans from creditors you should present a firm motivation. But, once I”ve got a short term loan, just because I was willing to buy a bike.