Wednesday, November 9, 2011

How to send parameters to WCF service


When developing a WCF service, chances are that the same service will serve various purposes. For example, the user might want to retrieve data in different formats or different representations.
When you have a WCF service, you most likely have an interface that defines the structure of the main class. For a RESTful service, you should have methods decorated with WebGet orWebInvoke. In that case, when you define the actual method and the WebGet attribute for it, you are able to specify anUriTemplate that would accept parameters.
Let’s take a look at an example.

1.[WebGet(UriTemplate="/GetDateTime")]
2.[OperationContract]
3.string GetDateTime();
This method will be called without any parameters, the endpoint being defined by /GetDateTime. So when a request is sent to that address, the method is executed. In case I’d like to make the method controllable by the client to some extent, I can open it for string parameters that can define the method behavior.
The method above is defined like this:

1.public string GetDateTime()
2.{
3.return DateTime.Now.ToString();
4.}
Since there can be parameters, different values can be returned based on the entered parameter. Therefore, I am going to modify the method definition in the interface to be just like this:

?
[WebGet(UriTemplate="/GetDateTime/{param}")]
2.[OperationContract]
3.string GetDateTime(string param);
Now, I don’t have a single endpoint defined (of course there is the base – GetDateTime) – the actions can be controlled by the string parameter that is passed to the method. So I modified my method accordingly:

01.public string GetDateTime(string param)
02.{
03.switch (param.Trim().ToLower())
04.{
05.case "now":
06.return DateTime.Now.ToString();
07.case "today":
08.return DateTime.Today.ToString();
09.case "utcnow":
10.return DateTime.UtcNow.ToString();
11.default:
12.return "Unknown parameter:" + param;
13.}
14.}
Depending on the parameter, the returned value will be different. I did not define an endpoint for the root location/GetDateTime, therefore if you access it without a parameter, a “Endpoint not found” error will be caused.
The parameter passed must be a string, so any conversions should be performed inside the method and not in the call. Also, if you want to pass a parameter array, you will have to manually split the single passed string into elements that represent specific parameters, depending on the delimiter you are going to use.