EziData Solutions

Web, NET and SQL Server

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