9.3. Returning Results in Different Formats

WDS services can return data in the following formats:

  • AtomPub

  • JSON

  • XML

AtomPub is the default format that is returned, and since WDS 1.5 you have control over how elements are mapped to AtomPub elements.

Let's look at how to return results in JSON format using jQuery and then how to access a WDS service from a console application.

9.3.1. Using JSON with JavaScript

JSON is a format commonly used by web applications since it is much less verbose than XML. JSON is also understood by many JavaScript frameworks and libraries. If you want to have WCF Data Services format your results as JSON, simply set the Accept header to application/json when making a request.

The following example shows how to use jQuery to retrieve the title of the first film in the set (for more information on jQuery, please refer to Chapter 12):

<script>
    function getMovieTitle() {
        $.ajax({
            type: "GET",
            dataType: "json",

url: "MovieService.svc/Films(1)",
            success: function (result) {
                alert(result.d.Title);
            },
            error: function (error) {
                alert('error '),
            }
        });
    }
</script>
<input type="button" Value="Get Movie Title"
       onclick="javascript:getMovieTitle();" />

But what JSON data will be returned by making the previous call? By using a web debugging proxy called Fiddler (www.fiddlertool.com), you can see what is returned. The following code shows the raw JSON:

{ "d" : {
"__metadata": {
"uri": "http://localhost/Chapter9/MovieService.svc/Films(1)", "type": "Models.Film"
}, "FilmID": 1, "Title": "Kung Fu Panda", "Description": "Classic martial arts tale", "Length": 120, "FilmShowings": {
"__deferred": {
"uri": " http://localhost/Chapter9/MovieService.svc/Films(1)/FilmShowings"
}
}
} }

Notice how the results were wrapped by an object called d. This is to prevent cross-site request forgery (CSRF); see Chapter 11 for more details on this.

9.3.2. Using JSON with C#

The following code shows how to retrieve results formatted as JSON using the HttpWebRequest class in C#:

System.Net.HttpWebRequest Request =
    (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(
      "http://localhost/Chapter9/MovieService.svc/Films(1)"
    );

Request.Method = "GET";

Request.Accept = "application/json";

System.Net.HttpWebResponse Response = (System.Net.HttpWebResponse)Request.GetResponse();

using (System.IO.StreamReader sr = new System.IO.StreamReader(Response.GetResponseStream()))
{
    Console.WriteLine(sr.ReadToEnd());
}

Console.ReadKey();

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.135.178