In case you are developing WCF REST API
with GET operation and there is need to have provision for sending optional parameters, this post is for you. Earlier Microsoft
doesn't support this however with .NET Framework 4.0 this works smoothly. I
will show you how:
For example there are three
parameters(id, language, mode) that are always passed in the url and other one(type) is optional.
Request URL could be like this:
or
Handling at Service side will be as
follows:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyService
{
[WebGet(UriTemplate = "?id=ID&language=LanguageCode&mode=free")]
public string
GetValue(string id, string
language, string mode)
{
var type = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["type"];
if(type!=null)
{
return "Hi There "
+ ID + " " + LanguageCode + " "
+ mode + " " + type;
}
else
{
return "Hi There "
+ ID + " " + LanguageCode + " "
+ mode;
}
}
}
Request URL could be like this:
or
Handling at Service side will be as
follows:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyService
{
[WebGet(UriTemplate = "id/{ID}/language/{LanguageCode}/mode/{mode}")]
public string
GetValue(string ID,
string LanguageCode,
string mode)
{
var type = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["type"];
if(type!=null)
{
return "Hi There "
+ ID + " " + LanguageCode + " "
+ mode + " " + type;
}
else
{
return "Hi There "
+ ID + " " + LanguageCode + " "
+ mode;
}
}
}
Hope it helps you.