December 21, 2018 10:09 by
Peter
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=peter&lastname=scott
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=peter
Output2 - parameter1 Firstname:kamal LastName:
In the above output parameter1 is passed i.e firstname=peter but you wont get lastname parameter, because you didn't pass and its optional if u dont pass the parameter value and will take value as empty.
HostForLIFE.eu European WCF Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.