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
- [OperationContract]
- [WebGet(ResponseFormat = WebMessageFormat.Json)]
- public List<Place> GetPlaces(string Country)
- {
- // create a list of places
- List<Place> places = new List<Place>();
-
- places.Add(new Place {
- Name = "London",
- Country = "UK",
- Population = 7825200
- });
-
- places.Add(new Place {
- Name = "New York",
- Country = "USA",
- Population = 8175133
- });
-
- places.Add(new Place {
- Name = "Sydney",
- Country = "Australia",
- Population = 4391674
- });
-
- var results = from p in places
- where p.Country == Country
- select p;
-
- // return the list of places
- return results.ToList();
- }
- }
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}]