DCSIMG
WCF Services and AJAX - Gady Elkarif's Blog

Gady Elkarif's Blog

WCF Services and AJAX

WCF Services and Ajax

In this post I show a sample of a WCF 3.5 service which supports Json.

WebGetAttribute.ResponseFormat Property

The WebMessageFormat property determines the format of responses sent from a service operation. The two possibe values are Xml and Json.

The following example demonstrates how to set the ResponseFormatProperty:

[ServiceContract]

public interface IService

{

    [OperationContract]

    [WebGet(ResponseFormat = WebMessageFormat.Json)]

    String SayHello(String name);

}

The implementation of this service is simple:

public class Service : IService

{

    public String SayHello(String name)

    {

        return String.Format("Hello {0}", name);

    }

}

 

Web.Config

In Web.Config the service include webHttpBinding and jasonBehavior which contain the enableWebScript element.

 

The enableWebScript element enables the endpoint behavior that makes it possible to consume the service from ASP.NET AJAX web pages. This behavior should be used in conjunction with either <webHttpBinding> or <webMessgaeEncoding> binding element.

 

    <system.serviceModel>

        <services>

            <service behaviorConfiguration="ServiceBehavior" name="Service">

                <endpoint

                    address=""

                    binding="webHttpBinding"

                    behaviorConfiguration="jsonBehavior"

                    contract="IService"/>

                <endpoint

                    address="mex"

                    binding="mexHttpBinding"

                    contract="IMetadataExchange"/>

            </service>

        </services>

        <behaviors>

            <serviceBehaviors>

                <behavior name="ServiceBehavior">

                    <serviceMetadata httpGetEnabled="true"/>

                    <serviceDebug includeExceptionDetailInFaults="false"/>

                </behavior>

            </serviceBehaviors>

            <endpointBehaviors>

                <behavior name="jsonBehavior" >

                    <enableWebScript/>

                </behavior>

            </endpointBehaviors>

        </behaviors>

    </system.serviceModel> 

 

ClientPage.htm

The client page create an Ajax XMLHttpRequest object, construct the url to the service and prints the response.

 

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head></head>

<body>

<h1>AJAX WCF Sample</h1>

<form name="input">

    Name: <input type="text" name="name" onclick="sayHello();" />

    <div id="msg"></div>

</form>

 

<script type="text/javascript">

function sayHello()

{

    var xmlHttp;

    try

    {

        xmlHttp = new XMLHttpRequest();

    }

    catch (e)

    {

        try

        {

            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

        }

        catch (e)

        {

            try

            {

                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

            }

            catch (e)

            {

                var msg = "This sample only works";

                msg = msg + "in browsers with AJAX support.";

                alert(msg);

 

                return false;

            }

        }

    }

 

    xmlHttp.onreadystatechange = function()

    {

        if (xmlHttp.readyState == 4)

        {

            var mdiv = document.getElementById("msg");

            mdiv.innerHTML = (xmlHttp.responseText);

        }

    }

 

    var url = "Service.svc/";

    url = url + "SayHello?name=";

    url = url + document.input.name.value;

 

    xmlHttp.open("GET", url, true);

    xmlHttp.send('');

}

</script>

</body>

</html> 

 

The result

 

WCF Ajax

The source for this sample can be downloaded from here.

 

 

 

 

פורסם: Jan 31 2008, 03:31 PM by egady | with 9 comment(s)
תגים:, ,

תוכן התגובה

Guy Burstein כתב/ה:

Well written!

Guy

# January 31, 2008 4:13 PM

Roy Elimelech כתב/ה:

What are the benefits of using json?

# January 31, 2008 8:12 PM

egady כתב/ה:

Browser deserialize Json faster than Xml. You can easily eval it into js, and traversing is more efficient than parsing Xml and using XPath.

Json also is supported by many Ajax toolkits.

When you have multiple asynchronous Ajax calls, like auto completion for example, with Json you can minimize data transfer.

With Json, cross domain scripting is easier.

# February 1, 2008 12:20 PM

AlexF כתב/ה:

We 're testing our .NET web services on all supported protocols, and trying to minimize the number of our test scenarios. So, all our tests are written in C# and use WCF with unified data/service contracts. Everything was sorta fine, and we were able to instantiate a proxy for the same service contract and different protocols for every protocol, but JSON. We were unable to make it work [yet].

Does someone know how to call a web service through WCF using JSON protocol?

# May 14, 2008 7:11 PM

egady כתב/ה:

Alex,

To call RESTFul service, try to use WebClient. If you need to post data, serialize it before sending using DataContractJsonSerializer and use WebClient.UploadString(...).

See blogs.microsoft.co.il/.../wcf-json-sending-complex-type-on-query-string.aspx

Gady.

# May 15, 2008 1:58 PM

Rami Heleg כתב/ה:

Hi,

i want to send parameter from type XML.

in your example and othr example i see how to send paarameter from type int, string etc... but if i try to send xml i failed from js.

hpw can i do that ?

# January 17, 2009 6:31 PM

egady כתב/ה:

Use WebMessageFormat.XML

# January 22, 2009 5:49 PM

ndtreviv כתב/ה:

I have an operation contract that receives a complex type. How do I get translation from the JSON-encoded object I'm sending to the OperationContract into that complex type? The "complex type" I'm talking about is a class decorated with the DataContract attribute whose members are also all decorated with the DataMember attribute.

eg, OperationContract is:

Boolean Create(DataList list);

DataList is a class decorated with [DataContract], with, for example a single member of type String called Name decorated with [DataMember].

When I post:

DataList:{Name:"Test Name"}

The method receives null.

Any ideas?

# May 7, 2009 10:57 AM

Sabino כתב/ה:

I have another question, what if I can not access directly to the WCF, I mean I have to access to the WCF with some external class, how can I implement this, any Idea ?

# September 5, 2009 7:19 AM
שלח תגובה

(שדה חובה)  

(שדה חובה)  

(אופציונלי)

(שדה חובה) 

Please add 5 and 1 and type the answer here:


Enter the numbers above: