WCF and optional parameters

I just started using WCF with REST and UriTemplates. Can additional parameters be used?

If not, what would you guys recommend to me for a system that has three parameters that are always used in the URL and others that are optional (variable amount)?

Example:

https://example.com/?id=ID&type=GameID&language=LanguageCode&mode=free 
  • id, type, language are always present
  • not required.
+15
rest optional-parameters wcf
Apr 25 2018-11-11T00:
source share
3 answers

I just tested it with WCF 4 and it worked without problems. If I do not use the mode in the query string, I will get null as the parameter value:

 [ServiceContract] public interface IService { [OperationContract] [WebGet(UriTemplate = "GetData?data={value}&mode={mode}")] string GetData(string value, string mode); } 

Method implementation:

 public class Service : IService { public string GetData(string value, string mode) { return "Hello World " + value + " " + mode ?? ""; } } 

For me, it looks like all query string parameters are optional. If the parameter is not present in the query string, it will have a default value for its type => null for string , 0 for int , etc. MS also states that this should be implemented.

In any case, you can always define a UriTemplate using id , type and language and access the optional parameters inside the WebOperationContext method:

 var mode = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["mode"]; 
+30
Apr 25 2018-11-18T00:
source share

I tried with additional parameters in a calm web service, If we do not pass anything in the parameter value, it remains equal to zero. After that we can check the null or empty function. If it is null, then do not use it, otherwise you can use it. Say I have below code

 [ServiceContract] public interface IService { [OperationContract] [WebGet(UriTemplate = "GetSample?part1={part1}&part2={part2}")] string GetSample(string part1, string part2); } 

Here part1 is required, and part2 is optional. Now the function will look like

 public class Service : IService { public string GetSample(string part1, string part2) { if (!string.IsNullOrEmpty(part2)) { return "Hello friends..." + part1 + "-" + part2; } return "Hello friends..." + part1; } } 

You can also do the conversion according to your requirements.

+2
Apr 26 2018-11-11T00:
source share

Should you use "?" then "/" in your URL.

Example:

 [WebGet(UriTemplate = "GetSample/?OptionalParamter={value}")] string GetSample(string part1); 
-one
Jun 23 '17 at 20:32
source share



All Articles