Sending parameters to a RESTful WCF service

DZone 's Guide to

Sending parameters to a RESTful WCF service

· Integration Zone ·
Free Resource

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 or WebInvoke. In that case, when you define the actual method and the WebGet attribute for it, you are able to specify an UriTemplate that would accept parameters.

Let’s take a look at an example.

[WebGet(UriTemplate="/GetDateTime")][OperationContract]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:

public string GetDateTime(){    return DateTime.Now.ToString();}

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}")][OperationContract]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:

public string GetDateTime(string param){    switch (param.Trim().ToLower())    {        case "now":            return DateTime.Now.ToString();        case "today":            return DateTime.Today.ToString();        case "utcnow":            return DateTime.UtcNow.ToString();        default:            return "Unknown parameter:" + param;    }}

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.

dotnet ,xml ,service ,visual studio ,rest ,parameters ,wcf ,c-sharp

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}