- WebGet(UriTemplate = "TestMessage/{p1}?firstname={firstname}&lastname={lastname}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Xml)]
- [OperationContract]
- string TestMessage(string message, string firstname = "", string lastname = "");
Whereas TestMessage is my service name and p1 parameter is compulsory whereas firstname and lastname parameters are optional but u have to specify in the URI Template but keep one thing in mind while declaring the parameters as optional u have to first preceed them with ? and then parameter name and then use & to assign the second parameter as option as per your requirement. If u see in the function declaration also i have used the optional parameter feature of .Net 4.0
Step 2 - Function Definition
- public string TestMessage(string message,string firstname="",string lastname="")
- {
- string responsedata = string.Empty;
- responsedata = message + "" + "FirstName: " + firstname + "" + "LastName: " + lastname;
- return responsedata;
- }
Note
How to call the Service,
Input1
http://localhost:49785/Service.svc/parameter1
Output1 - parameter1 Firstname: LastName
In the above output, only parameter1 will be returned as u didnot specify the other 2 parameters so they will get their value as "Empty"
Input2
http://localhost:49785/Service.svc/parameter1?firstname=kamal&lastname=rawat
Output2 - parameter1 Firstname:kamal LastName:rawat
so u will see in the above output u passed both the parameters so you got all the values.
Input2
http://localhost:49785/Service.svc/parameter1?firstname=kamal
Output2 - parameter1 Firstname:kamal LastName:
In the above output parameter1 is passed i.e firstname=kamal but you wont get lastname parameter, bcoz you didn't pass and its optional if u dont pass the parameter value and will take value as empty.
Thanks for reading..