EziData Solutions

Web, NET and SQL Server

Adding multiple parameters to JSON-enabled WCF service

One thing you’ll be tempted to do when you first start creating web services is to add multiple parameters to your web methods. Don’t, it will soon trip you up, especially if any of those parameters are complex types.

A better way to handle calling WCF web services that return JSON formatted results is to use Request and Response objects. Your WCF service accepts a single complex Request object that contains all the values it needs to perform its job. The results, along with any exceptions and messages are passed back to the caller in the Response object.

In this post, we’ll modify our GetPlaces method to use Request and Response objects instead of querystring parameters.

First add the following PlaceRequest and PlaceResponse classes.

Code Snippet
  1. public class PlaceRequest
  2. {
  3.     public string Country { get; set; }
  4.     public int MaxPopulation { get; set; }
  5. }

 

Code Snippet
  1. public class PlaceResponse
  2. {
  3.     public bool HasError { get; set; }
  4.     public string Status { get; set; }
  5.     public List<Place> Results { get; set; }
  6. }

Then modify the GetPlace method as follows.

Code Snippet
  1. [OperationContract]
  2.         [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
  3.         public PlaceResponse GetPlaces(PlaceRequest Request)
  4.         {
  5.             // instantiate our response object
  6.             PlaceResponse response = new PlaceResponse();
  7.  
  8.             // create a list of places
  9.             List<Place> places = new List<Place>();
  10.  
  11.             places.Add(new Place {
  12.                 Name = "London",
  13.                 Country = "UK",
  14.                 Population = 7825200
  15.             });
  16.  
  17.             places.Add(new Place {
  18.                 Name = "New York",
  19.                 Country = "USA",
  20.                 Population = 8175133
  21.             });
  22.  
  23.             places.Add(new Place
  24.             {
  25.                 Name = "Los Angeles",
  26.                 Country = "USA",
  27.                 Population = 3862839
  28.             });
  29.  
  30.             places.Add(new Place {
  31.                 Name = "Sydney",
  32.                 Country = "Australia",
  33.                 Population = 4391674
  34.             });
  35.  
  36.             var results = from p in places
  37.                           where p.Country == Request.Country && p.Population < Request.MaxPopulation
  38.                           select p;
  39.  
  40.             response.Results = results.ToList();
  41.  
  42.             // return the response
  43.             return response;
  44.         }

You’ll notice that we’ve changed the WebGet tag to WebInvoke. This declaration enables us to use the HTTP POST verb, instead of GET, since the calling function will be sending a complex object in the request body, not just a parameter in the URL. 

To test this web service you’ll need to create a POST HTTP request. The easiest way to do this is use a tool such as Fiddler to create the request.

Add Content-Type:application/json to the request header and specify the body as such:

{"Request":{"Country":"USA", "MaxPopulation":"4000000"}}

You’ll notice the values for Country and MaxPopulation are enclosed in an object called Request. This is because the web method parameter is called Request.

If everything goes well, Fiddler will report a response that includes the following JSON.

{"HasError":false,"Results":[{"Country":"USA","Name":"Los Angeles","Population":3862839}],"Status":null}
Posted: Feb 15 2012, 17:41 by CameronM | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: ASP.NET | C#

Adding Parameters to JSON-enabled WCF service

In the previous post we looked at how you configure a WCF web service to return JSON-formatted results. In this post we’ll look at how you can handle methods that need parameters.

We’re going to add a parameter to our GetPlaces method that will be used to filter the results based on the Country property. 

Code Snippet
  1.     [OperationContract]
  2.     [WebGet(ResponseFormat = WebMessageFormat.Json)]
  3.     public List<Place> GetPlaces(string Country)
  4.     {
  5.         // create a list of places
  6.         List<Place> places = new List<Place>();
  7.  
  8.         places.Add(new Place {
  9.             Name = "London",
  10.             Country = "UK",
  11.             Population = 7825200
  12.         });
  13.  
  14.         places.Add(new Place {
  15.             Name = "New York",
  16.             Country = "USA",
  17.             Population = 8175133
  18.         });
  19.  
  20.         places.Add(new Place {
  21.             Name = "Sydney",
  22.             Country = "Australia",
  23.             Population = 4391674
  24.         });
  25.  
  26.         var results = from p in places
  27.                       where p.Country == Country
  28.                       select p;
  29.  
  30.         // return the list of places
  31.         return results.ToList();
  32.     }
  33. }

Run the web service in the browser and add the parameter name and value as below:

http://localhost:57128/PlaceService.svc/GetPlaces?Country=USA

The response will be the filtered array of Place objects matching the parameter (New York).

[{"Country":"USA","Name":"New York","Population":8175133}]


Posted: Feb 14 2012, 03:21 by CameronM | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: ASP.NET

Return JSON from WCF Web Service

JSON is a popular, light-weight method of formatting data destined for mobile devices. Many popular APIs default to JSON formatted responses, so it’s a good practice to follow.

If you are retrofitting existing WCF web services to return JSON it easy on paper, but can be painful in practice. In this post, we’ll add a JSON friendly WCF service to an existing web application and point out some of the gotchas that can make your life hell.

Firstly, add an AJAX enabled web service to your ASP.NET web application. Visual Studio will add a default web method and make a number of changes to your web config. We’re going to create a method the will return some information about places around the world, so call the web service PlaceService.

Create a simple class to represent the places, this should be in a separate cs file, but for ease of use, I’m adding it after the closing tag of our PlaceService.

Code Snippet
  1. public class Place
  2. {
  3.     public string Name { get; set; }
  4.     public string Country { get; set; }
  5.     public int Population { get; set; }
  6. }

Delete the existing DoWork method and replace it with this code GetPlaces. 

Code Snippet
  1. [ServiceContract(Namespace = "")]
  2. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  3. public class PlaceService
  4. {
  5.     [OperationContract]
  6.     [WebGet(ResponseFormat = WebMessageFormat.Json)]
  7.     public List<Place> GetPlaces()
  8.     {
  9.         // create a list of places
  10.         List<Place> places = new List<Place>();
  11.  
  12.         places.Add(new Place {
  13.             Name = "London",
  14.             Country = "UK",
  15.             Population = 7825200
  16.         });
  17.  
  18.         places.Add(new Place {
  19.             Name = "New York",
  20.             Country = "USA",
  21.             Population = 8175133
  22.         });
  23.  
  24.         places.Add(new Place {
  25.             Name = "Sydney",
  26.             Country = "Australia",
  27.             Population = 4391674
  28.         });
  29.  
  30.  
  31.         // return the list of places
  32.         return places;
  33.     }
  34.  
  35. }

View the page in the web browser and add the name of the method to the URL like so: http://localhost:57128/PlaceService.svc/GetPlaces 

Depending on what browser you use, you’ll either be prompted to download the JSON document, or the browser will display the JSON  directly.

{"d":[{"__type":"Place:#FileAccess.Web","Country":"UK","Name":"London","Population":7825200},{"__type":"Place:#FileAccess.Web","Country":"USA","Name":"New York","Population":8175133},{"__type":"Place:#FileAccess.Web","Country":"Australia","Name":"Sydney","Population":4391674}]}

 

Getting rid of the “d”

Our results are certainly JSON formatted but you’ll notice that they are wrapped in an object called “d”, short for data. Ideally, we want to get rid of the d and simply return an array of Place objects. This is done by modifying the web.config.

Sometimes it seems like configuring your web.config is a dark art, known only to a few souls. Thankfully, this change if pretty easy as all we need to do if modify the endpoint behaviour Visual Studio created for us. Look for the PlaceServiceAspNetAjaxBehavior and insert a tag to enable web HTTP. The modified config will look something like this (your namespace will be different).

Code Snippet
  1. <endpointBehaviors>
  2.   <behavior name="MyWebApplication.PlaceServiceAspNetAjaxBehavior">
  3.     <enableWebScript />
  4.     <webHttp />
  5.   </behavior>
  6. </endpointBehaviors>

Run the web service again and this time we’ll have a better response.

[{"Country":"UK","Name":"London","Population":7825200},{"Country":"USA","Name":"New York","Population":8175133},{"Country":"Australia","Name":"Sydney","Population":4391674}]   


Posted: Feb 12 2012, 01:03 by CameronM | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: ASP.NET